0

I have this xml file:

<table head="Film">
<row>
    <id>USD</id><jan>Jan</jan><feb>Feb</feb><mar>Mar</mar><apr>Apr</apr><maj>May</maj><jun>Jun</jun><jul>Jul</jul><aug>Aug</aug><sep>Sep</sep><okt>Oct</okt><nov>Nov</nov><dec>Dec</dec><sum>Year</sum>
</row>
<row>
    <id>2018</id><jan>7629</jan><feb>6433</feb><mar>5573</mar><apr>3676</apr><maj>2545</maj><jun>2542</jun><jul>266</jul><aug>276</aug><sep>2690</sep><okt>371</okt><nov>5446</nov><dec>754</dec><sum>52731</sum>
</row>

I'm trying to extract the individual values for every month. I've tried

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.Load("model.xml"); 
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("table");
foreach (XmlNode node in nodeList) // for each <testcase> node
{
    Console.WriteLine(node["row"].InnerText);
}

This gives an exception because node["row"] is empty.

Any ideas?

2 Answers 2

1

Firstly your XML is not valid. You need to have a </table> on there.

//In this example GetXml() just returns your XML
var doc = XDocument.Parse(GetXml());
var rows = doc.Descendants("table").Elements("row").ToList();

foreach(var element in rows[1].Elements()){
    Console.WriteLine(element?.Value);
}

Now this is just a basic example based of your XML. You would likely want it to be more robust. You will notice I am showing you this with LINQ, I feel it's more readable than XmlDocument.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked, thanks. The xml document I'm using is valid. I had posted a small part of it.
0

You need to loop through the child nodes to get your desired result as follow:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("model.xml");
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("table");
foreach (XmlNode node in nodeList) // for each <testcase> node
{
    foreach (XmlNode row in node.ChildNodes)
    {
        foreach (XmlNode mon in row.ChildNodes)
        {

        }
    }
}

1 Comment

Do you have a valid xml as you are missing </table> in your posted xml.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.