views:

833

answers:

2

I have an xml file that contains its element like

<ab:test>Str</ab:test>  

When i am trying to access it using the code

XElement tempElement = doc.Descendants(XName.Get("ab:test")).FirstOrDefault();

Its giving me error

System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Xml.XmlException: The ':' character, hexadecimal value 0x3A, cannot be included in a name.

How shld i access it?

+2  A: 

If you want to use namespaces, LINQ to XML makes that really easy:

XNamespace ab = "http://whatever-the-url-is";
XElement tempElement = doc.Descendants(ab + "test").FirstOrDefault();

Look for an xmlns:ab=... section in your document to find out which namespace URI "ab" refers to.

Jon Skeet
It works, but the problem is that value of xmlns:ab is generated dynamically based on time stamp. How can i get its value?
coure06
@coure06: The namespace URI is dynamic? That's pretty weird. But yes, you can get it by finding the attribute value for `XNamespace.Xmlns + "ab"` from whichever element declares it.
Jon Skeet
A: 

There is an overload of the Get method you might want to try that takes into account the namespace. Try this:

XElement tempElement = doc.Descendants(XName.Get("test", "ab")).FirstOrDefault();
dhulk
`ab` isn't the actual namespace here though - it's just the alias for the namespace. (I don't know the right terminology unfortunately.) LINQ to XML makes this easy with `XNamespace`. It's rare that you need to explicitly call `XName.Get` in LINQ to XML.
Jon Skeet
ah my mistake, thanks for the clarification
dhulk