2014-10-02 73 views
0

我在检索XML文件中的某些数据时遇到了一些困难。 这是我的XML是什么样子:XDocument.Descendants()返回NullReferenceException:未将对象引用设置为对象的实例

<?xml version="1.0" encoding="windows-1252"?> 
<hexML version="0.9"> 
<head> 
<title><![CDATA[Title ]]></title> 
<description/> 
<ftm date="2014-09-24T16:34:37 CET"/> 
</head> 
<body> 
    <press_releases> 
     <press_release id="1796257" language="fr" type="5"> 
      <published date="2014-06-19T11:55:09 CET"/> 
      <categories> 
      <category id="75" label="French" keywords="language"/> 
      </categories> 
      <headline><![CDATA[Test Release for Website 3]]></headline> 
      <main><![CDATA[TEXT XML DETAILLE]]></main> 
      <footer><![CDATA[]]></footer> 
      <files> 
       <file id="618383" format="pdf" type="Regular Attachment"> 
       <file_headline><![CDATA[Test Attachment]]></file_headline> 
       <location><![CDATA[http://test.html1796257/618383.pdf]]></location> 
       </file> 
      </files> 
      <location href="/S/151406/1796257.xml"/> 
     </press_release> 
    </press_releases> 
</body> 
</hexML> 

我试图让这样的数据:http://test.html1796257/618383.pdf(在 “文件” 标签)

这是我试过到目前为止:

  string Linkpdf = (from c in DetailXml.Descendants("files")         
          select c.Element("location").Value).Single(); 

这会返回上面提到的异常。 感谢您的帮助

+0

有你使用调试器检查“DetailXml”不是“null”? – 2014-10-02 13:02:44

+0

是的,它不是空的,因为我正在做几个LINQ到XML请求,只有这个不工作... – Slrg 2014-10-02 13:03:53

+0

尝试交换'Single'和'Value' – bubbinator 2014-10-02 13:05:46

回答

3

如果XML是正确缩进:

<files> 
    <file id="618383" format="pdf" type="Regular Attachment"> 
     <file_headline><![CDATA[Test Attachment]]></file_headline> 
     <location><![CDATA[http://test.html1796257/618383.pdf]]></location> 
    </file> 
</files> 

,你就可以清楚地看到,<location><file>元素的直接子内<files>

string Linkpdf = (from c in DetailXml.Descendants("files") 
        select c.Element("file").Element("location").Value).Single(); 
+0

argh,对不起。你是对的 – Slrg 2014-10-02 13:30:34

相关问题