Search code examples
c#xmlxmlreader

XML node name and attributes are not available


I have the following XML structure:

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<values>
    <bool key="Chapter_1.Boolean1.value">true</bool>
    <string key="Chapter_1.Text1.value">abc</string>
    <string key="Chapter_1.Text2.value">Inspection done (2)</string>
    <number key="Chapter_1.Number1.value">128</number>
    <number key="Chapter_1.Number2.value">34539718</number>
    <number key="Chapter_1.Number3.value">3</number>
    <datetime key="Chapter_2.Chapter_2_1.DateTime1.value">2020-06-02T09:00:00+03:00</datetime>
    <datetime key="Chapter_2.Chapter_2_1.DateTime2.value">2016-02-05T00:00:00+02:00</datetime>
    <string key="Chapter_3.Text4.value">52</string>
    <string key="Chapter_3.Text5.value">22</string>
    <number key="Chapter_3.Number6.value">34539718</number>
</values>

and the following C# code:

var settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Auto;
settings.IgnoreWhitespace = true;
settings.IgnoreComments = true;

using (var xmlReader = new XmlTextReader(xmlFilePath))
{
    while (xmlReader.Read())
    {
        var nodeName = xmlReader.Name;
        var attrName = xmlReader.GetAttribute("key");
    }
}

The problem is that the node name is empty and there are no attributes for the following keys:

  • Chapter_1.Text1.value
  • Chapter_1.Number1.value
  • Chapter_3.Text5.value

Anyone has any idea what could be the problem?


Solution

  • The code worked well here, I was able to access all xml tags and attributes.

    Maybe you're confused because at each xmlReader.Read() it reads only one part of the tag. So to read all the tag with key "Chapter_1.Text1.value", first it reads a tag with name string and key "Chapter_1.Text1.value", then it reads something without a name, without a attribute, but with value "abc" and then it reads the tag closing with name string, but no attribute and no value.