0

My logic goes as follows: I want to find the first element that misses a given attribute, add the attribute and then find the next element which misses the element, add it and so fourth.

I find the first element missing the amount attribute in the following way:

    private XmlNode GetFirstElementWithoutAmount()
            {
                string productXPathQuery = "//XML/Products";
                XmlNodeList productList = ParentXmlDocument.SelectNodes(productXPathQuery);
                foreach (XmlNode element in productList)
                {
                    string passengerXPathQuery = "//XML/Products[ID=" + element.FirstChild.InnerText + "]/Amount";
                    var amount = element.SelectSingleNode(passengerXPathQuery);
                    if (amount == null)
                    {
                        return element;
                    }
                }

                return null;
     }

When I've found the first element missing the attribute, the amount is added in the following way:

private XmlNode GetOrCreateChildXMLNode(string NewNodeName, XmlNode ParentXMLNode)
        {

            if (ParentXMLNode == null)
            {
                return null;
            }

            XmlNode NewXMLNode = ParentXMLNode.SelectSingleNode("//" + NewNodeName);
            if (NewXMLNode == null)
            {
                NewXMLNode = ParentXmlDocument.CreateNode(XmlNodeType.Element, NewNodeName, string.Empty);
                ParentXMLNode.AppendChild(NewXMLNode);
            }

            return NewXMLNode;
        }

The problems is, that it only adds to the first element, and then the first function always returns the second element, even though there's more elements to come? Any ideas why this is?

Recusiwe
  • 1,594
  • 4
  • 31
  • 54
  • https://stackoverflow.com/questions/10053928/do-double-slash-in-xpath-predicate-work-the-same-as-in-the-path-itself is more or less canonical answer to "why when I search from the root (using `//`) it always finds the same node"... – Alexei Levenkov Dec 06 '19 at 01:25

1 Answers1

0

You are already inside //XML/Products during your foreach loop. Point directly to subnode.

string passengerXPathQuery = "./Amount";
Ed Bangga
  • 12,879
  • 4
  • 16
  • 30