Search code examples
c#xmlattributesselectsinglenode

get node value from node selected attribute


I have a noob problem. I select a node by its attribute and than I would like to get its children node value, but I always get the first node values instead. My xml:

<Sites>
  <Site ID="032">
    <Name>
    Rome
    </Name>
    <Code>
      ---
    </Code>
    <Visible>
      true
    </Visible>
</Site>
  <Site ID="040">
    <Name>
    Paris
    </Name>
    <Code>
      ---
    </Code>
    <Visible>
      true
    </Visible>
<Site>
  <Site ID="055">
    <Name>
    Berlin
    </Name>
    <Code>
      ---
    </Code>
    <Visible>
      true
    </Visible>
</Site>
</Sites>

My code:

XmlDocument xSite = new XmlDocument();
xSite.Load("Data\\Site.xml");
XmlNode siteNode = xSite.SelectSingleNode("/Sites/Site[@ID='" + _selectedSite.ID + "']");
string sitenodestr = siteNode.InnerText;
_selectedSite.Code = siteNode.SelectSingleNode("//Code").InnerText.Trim();
_selectedSite.Name = siteNode.SelectSingleNode("//Name").InnerText.Trim();
string visib = siteNode.SelectSingleNode("//Visible").InnerText.Trim();
_selectedSite.Visibility = Convert.ToBoolean(visib);

I checked and the ID is correct, and also siteNode content is correct, but I always get the Name of the first Site (rome in the example). can you help me?


Solution

  • It should be just not

    siteNode.SelectSingleNode("//Code")...
    

    but

    siteNode.SelectSingleNode("Code")...
    

    It is because //Code Xpath expression means "All "Code" elements in the document", but you need only children of siteNode.

    See Xpath syntax examples for reference.