locked
how to select child nodes in particular xml node?

    General discussion

  • how to select child nodes in particular xml node?

    i ve tried like this but it is returning nodes which are not in that node also so can anyone please help me with this

     public Folder(XmlNode folderNode)
            {
               
                foreach (XmlNode uploadTypeNode in folderNode.SelectNodes("//UploadType"))
    pavankumar kavety
    • Changed type Harry Zhu Wednesday, September 09, 2009 9:54 AM
    Wednesday, September 02, 2009 12:49 PM

All replies

  • Here is sample code:

    <Names>
        <Name>
            <FirstName>John</FirstName>
            <LastName>Smith</LastName>
        </Name>
        <Name>
            <FirstName>James</FirstName>
            <LastName>White</LastName>
        </Name>
    </Names>
    

    To get all <Name> nodes use XPath expression /Names/Name. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply index XmlNode with the node name: xmlNode["FirstName"].InnerText. See the example below.

    XmlDocument xml = new XmlDocument();
    xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"
    
    XmlNodeList xnList = xml.SelectNodes("/Names/Name");
    foreach (XmlNode xn in xnList)
    {
      string firstName = xn["FirstName"].InnerText;
      string lastName = xn["LastName"].InnerText;
      Console.WriteLine("Name: {0} {1}", firstName, lastName);
    }

    Please mark the post as answer if it is helpfull to you because it boosts the members to answer more and more.
    Wednesday, September 02, 2009 1:13 PM
  • thnx for the reply sudhir, for ex im having structure like this

    <doc>
    <Names class = a>
    <Name id=1>
    <FirstName>John</FirstName>
    <LastName>Smith</LastName>
    </Name>
    <Name id =2>
    <FirstName>James</FirstName>
    <LastName>White</LastName>
    </Name>
    </Names>
    <Names class = b>
    <Name id=3>
    <FirstName>John</FirstName>
    <LastName>Smith</LastName>
    </Name>
    <Name id =4>
    <FirstName>James</FirstName>
    <LastName>White</LastName>
    </Name>
    </Names>
    <doc>



    when im passing one node and when i try to get the child nodes of dat one it is giving me both the nodes .
    ie when i specify selectnodes it is returning me four nodes which are not in that particular node.

    pavankumar kavety
    Wednesday, September 02, 2009 1:32 PM
  • Two ways:

    node.ChildNodes

     

    node.SelectNodes("Names")

    Wednesday, September 02, 2009 4:49 PM
  • Are you targeting .NET 3.5? Then you can use Linq to XML to do this...

    www.insteptech.com ; msmvps.com/blogs/deborahk
    We are volunteers and ask only that if we are able to help you, that you mark our reply as your answer. THANKS!
    Wednesday, September 02, 2009 5:28 PM
  • Can you post your code here.
    Please mark the post as answer if it is helpfull to you because it boosts the members to answer more and more.
    Thursday, September 03, 2009 10:35 AM
  • We are changing the issue type to “General Discussion” because you have not followed up with the necessary information. If you have more time to look at the issue and provide more information, please feel free to change the issue type back to “Question” by opening the Options list at the top of the post  window, and changing the type. If the issue is resolved, we will appreciate it if you can share the solution so that the answer can be found and used by other community members having similar questions.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Wednesday, September 09, 2009 9:54 AM
  • Hi Pavan,

    If you want to get the child nodes of <Names class = a> then replace the following stmt in Sudhir's code

    XmlNodeList xnList = xml.SelectNodes("/Names/Name");

    with

    XmlNodeList xnList = xml.SelectNodes("/Names[@class='a']/Name");

    If you want to get the child nodes of <Names class = b>, use the following statement

    XmlNodeList xnList = xml.SelectNodes("/Names[@class='b']/Name");




    baskaran r
    Wednesday, September 09, 2009 1:47 PM
  • Insert code block isn't working...

     

    public

     

    static XmlNodeList SelectNodesFromChildren(XmlNode node, string

    xpath)

    {

     

    XmlDocument doc = new XmlDocument

    ();

    doc.LoadXml(node.OuterXml);

     

    return

    doc.SelectNodes(xpath);

    }

     

     


    Monday, March 21, 2011 2:55 AM
  • Your code doesn't add anything to that two-years-old thread.
    Monday, March 21, 2011 5:10 PM
  • Did you not read the code or something? The goal was to use an XPath statement to select from the ChildNodes of a specific node (not the entire XmlDocument). Am I mistaken in assuming that no one else accomplished this in the thread, or am I mistaken in assuming that I am correct and that you should retract or correct your previous statement?

    Here is an example to help out the one(s) having a hard time understanding the issue:

    <Action>
      <Label Type="Correct">
        <ThreadParticipant User="baskaran_rams">
      </Label>
    </Action>
    <Action>
      <Label Type="Correct">
        <RandomNodeStructure>
          <ThreadParticipant User="RUI Guy">
        </RandomNodeStructure>
      </Label>
    </Action>
    <Action>
      <Label Type="Incorrect">
        <ThreadParticipant User="Louis.fr">
          <Justification Desc="False Positive"/>
        </ThreadParticipant>
      </Label>
    </Action>

    Now, if I have the second action node in an object (XmlNode action2 let's say) and I attempt to action2.SelectNodes("//ThreadParticipant"), it returns all of the ThreadParticipants (which was the issue with your code and why it wasn't marked as an answer... did you not actually test the code?).

    On the other hand, if I have the same scenario and execute SelectNodesFromChildren(action2, "//ThreadParticipant"), oh my gosh... it returns the ThreadParticipant node for RUI Guy! Nice.

    But who knows, maybe your .Net framework is different than mine, or maybe I just misunderstood the original question.

     


    • Edited by RUI Guy Tuesday, March 22, 2011 12:27 AM
    Tuesday, March 22, 2011 12:10 AM
  • And just as a followup, I believe this solution only works when reading the XmlNode. I will make the full disclosure here that I haven't attempted to update the values and write back to the original XmlDocument and I'm not sure it would work.

    Of course, it is best to identify each node with some type of attribute so you don't have to create another XmlDocument, but when you need this specific functionality, this solution works well.

    Tuesday, March 22, 2011 12:24 AM
  • First, please accept my apologies. My reply may look a bit abrupt. It wasn't as rough in my head before I typed it.

    Your code certainly works like you want but it doesn't really return the nodes actually described by the XPath. Why would you start an XPath with / if you want a relative XPath?

    Wednesday, March 23, 2011 2:09 AM
  • This thread is a top search result for "XMLNode select subnode", but it does not have an answer that worked for me.

    I found what worked for me on StackOverflow.

    http://stackoverflow.com/questions/558870/xpath-selectnodes-in-net

    Basically, a quote from the XPath spec:

    • //para selects all the para descendants of the document root and thus selects all para elements in the same document as the context node
    • .//para selects the para element descendants of the context node

    So, the above code would change to:

     public Folder(XmlNode folderNode)
            {
                
                foreach (XmlNode uploadTypeNode in folderNode.SelectNodes(".//UploadType"))

    And that seems to work as expected.

     

    Thursday, December 15, 2011 3:33 PM
  • can we use this pattern  for multiple nodes ?
    Thursday, October 18, 2012 2:17 PM