1

I have xml which contain xml namespace. i need to get value from its xml node

<personxml:person xmlns:personxml="http://www.your.example.com/xml/person" xmlns:cityxml="http://www.my.example.com/xml/cities">
<personxml:name>Rob</personxml:name>
<personxml:age>37</personxml:age>
<cityxml:homecity>
    <cityxml:name>London</cityxml:name>
    <cityxml:lat>123.000</cityxml:lat>
    <cityxml:long>0.00</cityxml:long>
</cityxml:homecity>

Now i want to get value of tag <cityxml:lat> as 123.00

Code :

string xml = "<personxml:person xmlns:personxml='http://www.your.example.com/xml/person' xmlns:cityxml='http://www.my.example.com/xml/cities'><personxml:name>Rob</personxml:name><personxml:age>37</personxml:age><cityxml:homecity><cityxml:name>London</cityxml:name><cityxml:lat>123.000</cityxml:lat><cityxml:long>0.00</cityxml:long></cityxml:homecity></personxml:person>";
var elem = XElement.Parse(xml);
var value = elem.Element("OTA_personxml/cityxml:homecity").Value;

Error i am getting

The '/' character, hexadecimal value 0x2F, cannot be included in a name.
1
  • what about trying something like this elem.SelectSingleNode("/cityxml:homecity/@value").Value Commented Sep 10, 2014 at 14:52

3 Answers 3

1

You need to use XNamespace. For example:

XNamespace ns1 = "http://www.your.example.com/xml/person";
XNamespace ns2 = "http://www.my.example.com/xml/cities";

var elem = XElement.Parse(xml);
var value = elem.Element(ns2 + "homecity").Element(ns2 + "name").Value;

//value = "London"

Create XNamespace using a string that contains the URI, then combine the namespace with the local name.

For more information, see here.

Sign up to request clarification or add additional context in comments.

2 Comments

how to get only name as London ?
@Shaggy var value = elem.Element(ns2 + "homecity").Element(ns2 + "name").Value;
1

You are better off using a XmlDocument to navigate your xml.

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        XmlNode node = doc.SelectSingleNode("//cityxml:homecity/cityxml:lat");
        string latvalue = null;
        if (node != null) latvalue = node.InnerText;

Comments

1

The error I got with your code was that there needs to be a namespace to parse the XML properly Try :

 XNamespace ns1 = "http://www.your.example.com/xml/cities";
 string value = elem.Element(ns1 + "homecity").Element(ns1 + "name").Value;

I would still advice using XDocuments to parse if possible, but the above is fine if your way is a must.

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.