c# – Can't figure out how to write and read XML

Question:

There is a document of the following type:

  <?xml version="1.0"?>
<Settings>
  <section idCat="section1">
    <key1>value</key1>
    <key2>value</key2>
    <key3>value</key3>
  </section>

  <section idCat="section2">
    <key1>value</key1>
    <key2>value</key2>
    <key3>value</key3>
  </section> 
</Settings>

The task is to write a key-value pair into a certain category, and also read such a pair from a certain category. I'm confused about endless XmlDocument, XPathNavigator and so on, please help me figure it out. C # language.

Answer:

If you don't want to bother with all the features of XML-DOM, then try using LiNQtoXML. System.Xml.Linq namespace, The main working class is XElement .

Loading source Xml:

var myDoc = XElement.Load("myFile.xml");

You can also use the static method XElement.Parse(string) if you are using a string as the source.

We are looking for the required element:

var element = myDoc.Descendants("elementName").FirstOrDefault();

We read and write the value of the element:

var elValue = element?.Value;
element.Value = "newValue";//элемент должен существовать

We read and write the attribute:

var attrValue = element?.Attribute("attrName")?.Value;
element.Attribute("attrName").Value = "newAttrValue";

Add a nested element with a text value and an attribute

element.Add(new XElement("subElement", "value", new XAttribute("attrName","AttrValue"));

Save the result to disk

myDoc.Save("fileName")

As you can see, everything is quite transparent and understandable. XMLtoLiNQ fully supports the classic XML-DOM, but does so in a more elegant way than the older approach implemented in XmlDocument and its companion classes.

The documentation on the links below contains enough examples to figure it out and links to the description of the companion classes.
XDocument class
XElement class

Scroll to Top