サーチ…


基本的なXML文書の対話

public static void Main()
{
    var xml  = new XmlDocument();
    var root = xml.CreateElement("element");
        // Creates an attribute, so the element will now be "<element attribute='value' />"
        root.SetAttribute("attribute", "value");

    // All XML documents must have one, and only one, root element        
    xml.AppendChild(root);

    // Adding data to an XML document
    foreach (var dayOfWeek in Enum.GetNames((typeof(DayOfWeek))))
    {
        var day = xml.CreateElement("dayOfWeek");
            day.SetAttribute("name", dayOfWeek);

        // Don't forget to add the new value to the current document!
        root.AppendChild(day);
    }

    // Looking for data using XPath; BEWARE, this is case-sensitive
    var monday = xml.SelectSingleNode("//dayOfWeek[@name='Monday']");
    if (monday != null)
    {
        // Once you got a reference to a particular node, you can delete it
        // by navigating through its parent node and asking for removal
        monday.ParentNode.RemoveChild(monday);
    }
        
    // Displays the XML document in the screen; optionally can be saved to a file
    xml.Save(Console.Out);
}

XML文書からの読み込み

XMLファイルの例

    <Sample>
    <Account>
        <One number="12"/>
        <Two number="14"/>
    </Account>
    <Account>
        <One number="14"/>
        <Two number="16"/>
    </Account>
    </Sample>

このXMLファイルからの読み込み:

    using System.Xml;
    using System.Collections.Generic;
    
    public static void Main(string fullpath)
    {
        var xmldoc = new XmlDocument();
        xmldoc.Load(fullpath);
        
        var oneValues = new List<string>();
        
        // Getting all XML nodes with the tag name
        var accountNodes = xmldoc.GetElementsByTagName("Account");
        for (var i = 0; i < accountNodes.Count; i++)
        {
            // Use Xpath to find a node
            var account = accountNodes[i].SelectSingleNode("./One");
            if (account != null && account.Attributes != null)
            {
                // Read node attribute
                oneValues.Add(account.Attributes["number"].Value);
            }
        }
}

XmlDocumentとXDocument(例と比較)

Xmlファイルと対話するにはいくつかの方法があります。

  1. XML文書
  2. XDocument
  3. XmlReader / XmlWriter

LINQ to XMLの前に、属性、要素などを追加するようなXML操作のためにXMLDocumentが使用されました。 LINQ to XMLは、XDocumentを同じ種類のものに使用します。構文はXMLDocumentよりはるかに簡単で、最小限のコードしか必要としません。

また、XDocumentはXmlDocumentのように高速です。 XmlDoucumentは、XMLドキュメントをクエリするための古くて汚いソリューションです。

XmlDocumentクラスXDocumentクラスクラスの例をいくつか紹介します。

XMLファイルを読み込む

string filename = @"C:\temp\test.xml";

XmlDocument

XmlDocument _doc = new XmlDocument();
_doc.Load(filename);

XDocument

XDocument _doc = XDocument.Load(fileName);

XmlDocumentを作成する

XmlDocument

XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
root.SetAttribute("name", "value");
XmlElement child = doc.CreateElement("child");
child.InnerText = "text node";
root.AppendChild(child);
doc.AppendChild(root);

XDocument

 XDocument doc = new XDocument(
    new XElement("Root", new XAttribute("name", "value"), 
    new XElement("Child", "text node"))
);

/*result*/
<root name="value">
    <child>"TextNode"</child>
</root>

XML内のノードのInnerTextを変更する

XmlDocument

XmlNode node = _doc.SelectSingleNode("xmlRootNode");
node.InnerText = value;

XDocument

 XElement rootNote = _doc.XPathSelectElement("xmlRootNode"); 
rootNode.Value = "New Value";

編集後のファイルの保存

変更後は必ずxmlを安全にしてください。

// Safe XmlDocument and XDocument
_doc.Save(filename);

XMLからのリトリーブ値

XmlDocument

 XmlNode node = _doc.SelectSingleNode("xmlRootNode/levelOneChildNode");
string text = node.InnerText;

XDocument

 XElement node = _doc.XPathSelectElement("xmlRootNode/levelOneChildNode");
 string text = node.Value;

すべての子要素から値を取得し、attribute = somethingの値を返します。

XmlDocument

List<string> valueList = new List<string>(); 
    foreach (XmlNode n in nodelist)
    {
        if(n.Attributes["type"].InnerText == "City")
        {
            valueList.Add(n.Attributes["type"].InnerText);
        }
    }

XDocument

var accounts = _doc.XPathSelectElements("/data/summary/account").Where(c => c.Attribute("type").Value == "setting").Select(c => c.Value);

ノードを追加する

XmlDocument

XmlNode nodeToAppend = doc.CreateElement("SecondLevelNode");
nodeToAppend.InnerText = "This title is created by code";

/* Append node to parent */
XmlNode firstNode= _doc.SelectSingleNode("xmlRootNode/levelOneChildNode");
firstNode.AppendChild(nodeToAppend);

/*After a change make sure to safe the document*/
_doc.Save(fileName);

XDocument

_doc.XPathSelectElement("ServerManagerSettings/TcpSocket").Add(new XElement("SecondLevelNode"));

 /*After a change make sure to safe the document*/
_doc.Save(fileName); 


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow