3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C#のLinq to xmlでxmlの作成を行う

Last updated at Posted at 2020-04-27

C#でxmlの作成を行ったので方法を残す

#属性のあるxml要素の構築
要素はXElement、属性はXAttributeを使う

xml.cs
XElement element =
    new XElement("person",  
        new XElement("person",
        new XAttribute("Type", "engineer"),
            new XElement("Name", "Yamada Taro"),
            new XElement("skill",
                new XElement("language", "C#")
           )
       )
   );

xml出力したもの

test.xml
<person>  
  <person Type="engineer">  
    <Name>Yamada Taro</Name>  
    <skill>  
      <language>C#</language>  
    </skill>  
  </person>  
</person>  

#namesapceがある場合
XNamespaceでnamespaceを定義する

XNamespace ns= "http://www.test";
xml2.cs
XElement element =
    new XElement("person",  
        new XAttribute(XNamespace.Xmlns + "ns", ns),
        new XElement("person",
        new XAttribute("Type", "engineer"),
            new XElement(ns + "Name", "Yamada Taro"),
            new XElement("skill",
                new XElement("language", "C#")
           )
       )
   );

xml出力したもの

test2.xml
<person xmlns:ns="http://www.test" >  
  <person Type="engineer">  
    <ns:Name>Yamada Taro</Name>  
    <skill>  
      <language>C#</language>  
    </skill>  
  </ns:person>  
</person>  

#既存のxmlに要素を追加する場合
要素を追加したいxmlを読み込み、追加したい位置を指定

 XElement xml = XElement.Load(test.xml);
 XElement child1 = xmlTree.Element("Name");  
 child1.AddAfterSelf(  
    new XElement("ID", 10)  
 );  

Nameの後ろにIDが追加される

test.xml
<person>  
  <person Type="engineer">  
    <Name>Yamada Taro</Name>  
    <ID>10</Id>  
    <skill>  
      <language>C#</language>  
    </skill>  
  </person>  
</person>  

参考
https://docs.microsoft.com/ja-jp/dotnet/csharp/programming-guide/concepts/linq/creating-xml-trees-linq-to-xml-2

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?