Szukaj…


Podstawowa interakcja dokumentu 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);
}

Czytanie z dokumentu XML

Przykładowy plik XML

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

Czytanie z tego pliku 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 vs XDocument (Przykład i porównanie)

Istnieje kilka sposobów interakcji z plikiem Xml.

  1. Dokument Xml
  2. XDocument
  3. XmlReader / XmlWriter

Przed LINQ do XML używaliśmy XMLDocument do manipulacji w XML, takich jak dodawanie atrybutów, elementów i tak dalej. Teraz LINQ to XML używa XDocument do tego samego rodzaju rzeczy. Składnie są znacznie łatwiejsze niż XMLDocument i wymagają minimalnej ilości kodu.

Również XDocument jest mutch szybszy niż XmlDocument. XmlDoucument to stare i brudne rozwiązanie do wysyłania zapytań do dokumentu XML.

Pokażę kilka przykładów klasy XmlDocument i klasy klasy XDocument :

Załaduj plik XML

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

XmlDocument

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

XDocument

XDocument _doc = XDocument.Load(fileName);

Utwórz 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>

Zmień tekst wewnętrzny węzła w XML

XmlDocument

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

XDocument

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

Zapisz plik po edycji

Pamiętaj o zabezpieczeniu xml po każdej zmianie.

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

Odzyskaj wartości z XML

XmlDocument

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

XDocument

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

Odzyskaj wartość od wszystkich ze wszystkich elementów potomnych, w których atrybut = coś.

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

Dołącz węzeł

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
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow