1
<root>
 <A testId ="test">
    <B  id="ABC">one
    </B>
    <B id="ZYZ">two
    </B>
    <B  id="QWE">three
    </B>
    <B>four
    </B>
  </A>
</root>

Need to extract attribute value of testId for the node <A>.I'm using following c# code but, its throwing null exception.

doc.XPathSelectElement("//A/@testId")

Any help appreciated!

2 Answers 2

5

You can't get attributes with XPath (actually XPathSelectElement method names states, that its purpose is selecting element). So, you should select element, and then get its attribute (assume you are using Linq to XML. If not I suggest you to start doing this):

(string)doc.XPathSelectElement("//A").Attribute("testId")

Actually there is no benefit of XPath usage in this case:

(string)doc.Root.Element("A").Attribute("testId")
Sign up to request clarification or add additional context in comments.

2 Comments

don't you think .value is required after Attribute("testId")?
@Neel nope - usage of casting is safer than access to Value property. If attribute or element is not found, then .Value will throw NullReferenceException
0

Suppose you have xml file XMLFile1.xml then try below code it will give u result test

 XDocument xDoc = XDocument.Load("XMLFile1.xml");
 var test = xDoc.Root.Element("A").Attribute("testId").Value;

Update :-

As suggested by Sergey usage of casting is safer than access to Value property so updated code as below

var test = (string)xDoc.Root.Element("A").Attribute("testId");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.