Linq-to-XML with XDocument namespace issue

2019-05-27 02:46发布

I have this XML document:

<?xml version="1.0" encoding="utf-8"?>
<directoryresponse xmlns="https://www.sisow.nl/Sisow/REST" version="1.0.0">
  <directory>
    <issuer>
      <issuerid>01</issuerid>
      <issuername>ABN Amro Bank</issuername>
    </issuer>
    <issuer>
      <issuerid>02</issuerid>
      <issuername>ASN Bank</issuername>
    </issuer>
  </directory>
</directoryresponse>

And this does not work:

var banks = doc.Descendants("issuer").Select(x => 
    new Bank(Convert.ToInt32(x.Element("issuerid").Value), x.Element("issuername").Value)).ToList();

But when I manual remove the directoryresponse xml namespace xmlns="https://www.sisow.nl/Sisow/REST" it works! The namespace url is a 404. So why doesn't the xdoc ignore the namespace if it's a 404?

This also does not work: var banks = doc.Elements().Where(e => e.Name.LocalName == "issuer" ).Select(...

The main question is: how can I modify my code so that it ignores the 404 namespace?

1条回答
虎瘦雄心在
2楼-- · 2019-05-27 03:24

The URL itself is irrelevant here - it's just a token for the namespace, really. I don't believe LINQ to XML will try to fetch it.

However, you need to use it to construct the XName to search for:

XNamespace ns = "https://www.sisow.nl/Sisow/REST";
var banks = doc.Descendants(ns + "issuer")
               .Select(x => new Bank((int) x.Element(ns + "issuerid"),
                                     (string) x.Element(ns + "issuername"))
               .ToList();
查看更多
登录 后发表回答