开发者

Why this LINQ to XML doesn't work?

开发者 https://www.devze.com 2023-04-06 21:29 出处:网络
I receive this XML from an external source: <epp xmlns=\"urn:ietf:params:xml:ns:epp-1.0\"> <response>

I receive this XML from an external source:

<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
  <response>
    <result code="1300">
      <msg>Command completed successfully; no messages</msg>
    </result>
    <trID>
      <clTRID>TEST-12345</clTRID>
      <svTRID>IRNIC_2011-09-21T13:44:25+04:30_f1u</svTRID>
    </trID>
  </response>
</epp>

I want to extract the value of the code attribute of the result element. I used this code:

XDocument doc = XDocument.Parse(response);
XNamespace ns = "urn:ietf:params:xml:ns:epp-1.0";
string value = doc.Descendants(ns + "result开发者_运维知识库").First().Attribute("code").Value;

However, it throws null value exception, because doc.Descendants(ns + "result") is null.

What's wrong here?


However, it throws null value exception, because doc.Descendants(ns + "result") is null

I would not expect doc.Descendants to ever return a null - it might return an empty sequence, but that wouldn't be a "null value exception". Likewise, First() - it either returns something, or it throws an exception (and while that "something" can be a null, I do not expect Descendants would be yielding nulls). So that leaves .Attribute("code").Value. Now yes; .Attribute("code") can return a null, if an attribute doesn't exist. If you are happy to obtain a null in those cases, I recommend:

string value = (string)doc.Descendants(ns + "result").First().Attribute("code");

the conversion operator handles null (non-existent) attributes.


No repro. Your code is basically OK.

So: Debug. Break the statement up and check things.

  • is your doc loaded OK ?
  • what does just doc.Descendants(ns + "result").First() deliver?
  • etc


Check response variable because i loaded the xml from an xml file and your code worked great.

In case of testing, you can save the response in an xml file and load it from there.

use XDocument.Load("a.xml") to load an xml file.


Tested this too. Easiest way to test is to download LinqPad, create new query, then for Language select "C# statement(s)" from the dropdown. Click Run, should work with the code provided. I would also check the response variable as suggested by "Rased Dot Net"

string xml =
@"<epp xmlns=""urn:ietf:params:xml:ns:epp-1.0"">
  <response>
    <result code=""1300"">
      <msg>Command completed successfully; no messages</msg>
    </result>
    <trID>
      <clTRID>TEST-12345</clTRID>
      <svTRID>IRNIC_2011-09-21T13:44:25+04:30_f1u</svTRID>
    </trID>
  </response>
</epp>";

XDocument doc = XDocument.Parse(xml);
Console.WriteLine(doc.ToString());
XNamespace ns = doc.Root.Name.Namespace;
Console.WriteLine("Namespace: " + ns.ToString());
string value = doc.Descendants(ns + "result").First().Attribute("code").Value;
Console.WriteLine(value);
0

精彩评论

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