Reputation: 115
i need to read the value of a particular value in an xml tag, of he solutions i tried i could only find that to get a value of a tag element ,i need to traverse from root element to the child element.is there an optiion where i can directly select a tag and get its value.
In the below xml exa,i need to get 123456 value from the xml using c#. Ex:-
<ForwardActionRequest xmlns:auth="test" xmlns="http://www.test">
<auth:Authentication>
<auth:AuthenticationData>
<auth:AuthenticationKey>test</auth:AuthenticationKey>
<auth:Username>test</auth:Username>
<auth:Password>test</auth:Password>
</auth:AuthenticationData>
</auth:Authentication>
<SearchOrderReference>
<Reference>123456</Reference>
<AllocatedBy>test</AllocatedBy>
<Description>test</Description>
</SearchOrderReference>
Upvotes: 1
Views: 992
Reputation: 2472
Try following code:
XDocument doc = XDocument.Load(yourXMLText);
var node = xmlDoc.SelectSingleNode("//SearchOrderReference[@Reference='123456']");
Then extract node's attribute to get the value of reference tag.
Upvotes: 0
Reputation: 12683
From your post using VS 2005 you can try the XML Reader which reads the XML from string. Here is an example.
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
reader.ReadToFollowing("SearchOrderReference");
reader.ReadToFollowing("Reference");
string r = reader.ReadInnerXml();
}
Upvotes: 0
Reputation: 41
You can deserialize the xml content into a class and directly get the value of the element or you can use LINQ to XML to retrieve the element value,
XDocument doc=XDocument.Load(XMLContent or XMLPath); string=doc.Element("SearchOrderReference").Element("Reference").Value;
Upvotes: 0
Reputation: 4849
Use XmlDocument.SelectSingleNode() to pass in an XPath that will describe the node you want and then extract the value. Use this prototype as you are using namespaces:
http://msdn.microsoft.com/en-us/library/h0hw012b(v=vs.110).aspx
Read about how to instantiate an XmlNamespaceManager() and initialize it with the relevant prefix (it needs not be what you have in the xml itself), then issue the following request:
XmlNode node = doc.SelectSingleNode("/t:ForwardActionRequest/t:SearchOrderReference/t:Reference");
Given that you associate "t" with "http://www.test".
Upvotes: 0
Reputation: 35822
You can use LINQ to XML:
XDocument doc = XDocument.Load(yourXMLText);
string value = doc.Element("SearchOrderReference").Element("Reference").Value;
Please note that I haven't tested this code.
I also encourage you to read more about LINQ to XML here.
Upvotes: 4