2014-10-02 64 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

相關問題