开发者

Get xelement value with namespaced xdocument in c#

I am not able to get xelement value if xdocument has namespace attribute. Here is my code:

string ts = @"<TestNameSpace xmlns='http://www.w3.org/2001/XMLSchema'>
  <requestID>
    <client>xxxx</client>
    <id>yyyy</id>
    <timestamp>zzzz</timestamp>
 </requestID>
</TestNameSpace>";
XDocument doc1 = XDocument.Parse(ts);
XElement reqID = doc1.Root.Element("requestID");

My problem is that reqID returns null data in the above c开发者_JAVA百科ode. If without xmlns attribute or empty value of xmlns, the reqID will get correct data.

Can anyone tell me what wrong in the above code?

Thank for advance.


You need to first define an XNamespace:

XNamespace ns = "http://www.w3.org/2001/XMLSchema";

and then use that in your query:

XDocument doc1 = XDocument.Parse(ts);
XElement reqID = doc1.Root.Element(ns + "requestID");


Try like this:

string xml = 
@"<TestNameSpace xmlns='http://www.w3.org/2001/XMLSchema'>
  <requestID>
    <client>xxxx</client>
    <id>yyyy</id>
    <timestamp>zzzz</timestamp>
 </requestID>
</TestNameSpace>";
var doc = XDocument.Parse(xml);
XNamespace ns = "http://www.w3.org/2001/XMLSchema";
var reqID = doc.Root.Element(ns + "requestID");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜