XmlDocument と System.Xml 名前空間

# XmlDocument と XDocument (例と比較)

Xml ファイルを操作する方法はいくつかあります。

    • XML ドキュメント
    • XDocument
    • 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); 
    
    

    # 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);
                }
            }
    }
    
    

    # 基本的な 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);
    }