User987123
User987123

Reputation: 97

Get values of XML nodes with foreach

I am working on a programm with C# and a XML-File. I want to read the values of the xml-nodes but I get an issue with that. In the second part, where I am trying to get the content, it only does one loop and not three. The first values are correct. I don't know why it only makes the first loop. I hope someone can help me.

My XML-File:

<?xml version="1.0" encoding="utf-8"?>
<lagerverwaltung>
  <article>
    <inventory id="1">
    </inventory>
    <orders>
      <order id="1">
        <id>1</id>
        <idposition>1</idposition>
        <content>
          <idarticle amount="4">2</idarticle>
          <idarticle amount="3">3</idarticle>
          <idarticle amount="2">1</idarticle>
        </content>
        <idcustomer>2</idcustomer>
        <orderdate>05.01.2018 15:10:44</orderdate>
        <paydate>05.02.2018</paydate>
        <mwst>7.7</mwst>
        <total>1781.358</total>
      </order>
    </orders>
  </article>
</lagerverwaltung>

My C#-Code:

List<Order> orderList = new List<Order>();
XmlDocument xml = new XmlDocument();
xml.Load(xmlFilePath);
XmlNodeList xnList = xml.SelectNodes("/lagerverwaltung/article/orders/order");
foreach (XmlNode xn in xnList)
{
    // Is working
    string id = xn["id"].InnerText;
    string bestellPositionId = xn["idposition"].InnerText;
    string kundeId = xn["idcustomer"].InnerText;
    string bestelldatum = xn["orderdate"].InnerText;
    string rechnungsDatum = xn["paydate"].InnerText;
    string mwst = xn["mwst"].InnerText;
    string rechnungsTotal = xn["total"].InnerText;


    XmlNodeList xnInhalt = xml.SelectNodes("/lagerverwaltung/article/orders/order[@id='" + id + "']/content");
    Dictionary<string, string> content= new Dictionary<string, string>();
    foreach (XmlNode xmlNode in xnInhalt) // Does only one loop
    {
        string articleid = xmlNode["idarticle"].InnerText;
        string amount = xmlNode["idarticle"].GetAttribute("amount");
        content.Add(articleid, amount);
    }
}

Upvotes: 0

Views: 1192

Answers (1)

Andy G
Andy G

Reputation: 19367

There is a single content node, use content/idarticle to get the inner collection:

XmlNodeList xnInhalt = xml.SelectNodes("/lagerverwaltung/article/orders/order[@id='" + id 
+ "']/content/idarticle");

You would then modify the following code because xmlNode now refers to an idarticle. For example,

string articleid = xmlNode.InnerText;

Upvotes: 3

Related Questions