-2

How can I assign values from this .xml file

<?xml version="1.0" encoding="utf-8"?>
<root>
    <Classic>
        <value1>6</value1>
        <value2>18.7</value2>
        <value3>1</value3>
    </Classic>
</root>

to a variable (integer, double) in a C# code? For example:

int x = value1;
double y = value2;
int z = value3;

Thanks in an advance for an answer, I've been looking for it for a long time now.

Leedy
  • 17
  • 5
  • 3
    Does this answer your question? [How do I read and parse an XML file in C#?](https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c) – Yong Shun May 24 '21 at 08:19

1 Answers1

1

You can use XmlDocument to load and query nodes. This works great if you know the exact nodes and the types.

There are lots of great articles about XML parsing in C# (https://learn.microsoft.com/en-us/dotnet/standard/data/xml/), and some good answers here: C# Parsing XML File

For your case, the parsing could be simplified like this:


    void Run()
    {
        string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <root>
              <Classic>
                <value1>6</value1>
                <value2>18.7</value2>
                <value3>1</value3>
              </Classic>
            </root>";
        var doc = new XmlDocument();
        doc.LoadXml(xml);

        var classicNode = doc.SelectSingleNode("/root/Classic");
        int x = int.Parse(classicNode.SelectSingleNode("value1").InnerText);
        double y = double.Parse(classicNode.SelectSingleNode("value2").InnerText);
        int z = int.Parse(classicNode.SelectSingleNode("value3").InnerText);

        Console.WriteLine($"{x}, {y}, {z}");
    }

Another approach is to use XDocument with XPathSelectElement extension

    void Run2()
    {
        string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <root>
              <Classic>
                <value1>6</value1>
                <value2>18.7</value2>
                <value3>1</value3>
              </Classic>
            </root>";
        var doc = XDocument.Parse(xml);
        int x = int.Parse(doc.XPathSelectElement("root/Classic/value1").Value);
        double y = double.Parse(doc.XPathSelectElement("root/Classic/value2").Value);
        int z = int.Parse(doc.XPathSelectElement("root/Classic/value3").Value);
    }
slacker
  • 509
  • 2
  • 6
  • 2
    While you *can* use `XmlDocument`, I'd definitely recommend LINQ to XML instead - it makes this significantly simpler. – Jon Skeet May 24 '21 at 08:36