如何使用linq C#读取复杂的XML

时间:2018-11-10 21:47:12

标签: c# xml linq

我想读取一个xml文件...当它是简单xml时,它可以很好地工作,但是当它是复杂xml时,它不起作用。例如:

简单的XML:

<?xml version="1.0" encoding="utf-8" ?>
<FILE>
  <CLIENTS>
    <CLIENT>
      <NAME>William</NAME>
      <AGE>25</AGE>
    </CLIENT>

    <CLIENT>
      <NAME>John</NAME>
      <AGE>31</AGE>
    </CLIENT>
  </CLIENTS>
</FILE>

C#:

XDocument document = XDocument.Load(path);
var clientNodes = from clt in document.Descendants("CLIENTS") select clt;
//This works and "clientNodes" has values for clients node

但是当我想加载更复杂的xml时,文件中的查询为空

复杂的XML:

<?xml version="1.0" encoding="UTF-8"?>

<SII:RESPONSE xmlns:SII="http://www.sii.cl/XMLSchema">

<SII:RESPONSE_STATUS>
    <SII:STATE>1</SII:STATE>
</SII:RESPONSE_STATUS>
<SII:RESPONSE_CONTENT>
    <CREATED_BY>
        <ID>233</ID>
        <NAME>Sophy</NAME>
    </CREATED_BY>
    <CLIENT>
        <NAME>William</NAME>
        <AGE>25</AGE>
    </CLIENT>
    <CLIENT>
        <NAME>John</NAME>
        <AGE>25</AGE>
    </CLIENT>
</SII:RESPONSE_CONTENT>

C#:

XDocument documentoXML = XDocument.Load(path);
var simpleNodes = from clt in document.Descendants(XName.Get("SII", "RESPONSE_CONTENT")) select clt;

//这不起作用,并且“ simpleNodes”没有值:(

请帮助!

1 个答案:

答案 0 :(得分:0)

应该是

XName.Get("RESPONSE_CONTENT", "http://www.sii.cl/XMLSchema")

或更简单:

XNamespace sii = "http://www.sii.cl/XMLSchema";

然后

document.Descendants(sii + "RESPONSE_CONTENT")