locked
Select Attribute Value Using Xpath RRS feed

  • Question

  • User364803292 posted

    Hello

    Suppose I have the following xml document:

    <RootNode>
      <ChildNode1 attribute1="test1" attribute2="test2">
        <ChildNode11 attribute1="subTest1" />
      </ChildNode1>
    </RootNode>
    XElement xmlFile = XElement.Load("C:/XMLs/xmlFileName.xml");
    

    How can I select the value of the attribute attribute1 of childNode11 using xpath?

    Friday, June 27, 2014 8:23 AM

Answers

  • User1918509225 posted

    Hi Taonias,

    You can use Linq To  Xml,Here is my code for you:

                XElement ex = XElement.Load(Server.MapPath("XMLFile1.xml"));
    
                IEnumerable<XNode> node = from ele in ex.DescendantNodes()
                                          select ele;
                foreach (XNode xn in node) {
                    if (xn is XElement) {
                        XElement xa = xn as XElement;
                        if (xa.Name=="ChildNode11")
                        {
                            foreach (XAttribute xatt in xa.Attributes()) {
                                string a = xatt.Value.ToString();
                            }
                        }
                    }

    Best Regards,

    Kevin Shen

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 30, 2014 3:12 AM

All replies

  • User-1360095595 posted

    Search for attribute here: http://msdn.microsoft.com/en-us/library/ms256086(v=vs.110).aspx

    Google/bing are your friends. Use them...

    Friday, June 27, 2014 5:37 PM
  • User364803292 posted
    And you think that I did not searched before posting here?
    The question was the start leading to my actual problem and that is why I used this example.

    If you dont want to answer then don't. Being 'smart' doesn't help anyone.

    Thank you for your time even though you were the opposite of helpful.
    Saturday, June 28, 2014 6:03 AM
  • User1918509225 posted

    Hi Taonias,

    You can use Linq To  Xml,Here is my code for you:

                XElement ex = XElement.Load(Server.MapPath("XMLFile1.xml"));
    
                IEnumerable<XNode> node = from ele in ex.DescendantNodes()
                                          select ele;
                foreach (XNode xn in node) {
                    if (xn is XElement) {
                        XElement xa = xn as XElement;
                        if (xa.Name=="ChildNode11")
                        {
                            foreach (XAttribute xatt in xa.Attributes()) {
                                string a = xatt.Value.ToString();
                            }
                        }
                    }

    Best Regards,

    Kevin Shen

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 30, 2014 3:12 AM