繁体   English   中英

XDocument.Descendants()返回NullReferenceException:未将对象引用设置为对象的实例

[英]XDocument.Descendants() returns NullReferenceException : Object reference not set to an instance of an object

我在检索XML文件中的某些数据时遇到一些困难。 这是我的XML的样子:

<?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();

这使我返回上面提到的异常。 谢谢你的帮助

如果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><files><file>元素的直接子元素:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM