xml.DocumentElement.SelectSingleNode中的空引用错误

时间:2016-04-20 13:54:19

标签: c# xml httprequest

我向网站发送了一个帖子请求。回到响应为xml我试图从xml节点获取一个值,这是代码

            XmlDocument xml = new XmlDocument();

           xml.LoadXml(PhishTankRequest);

            status = xml.DocumentElement.SelectSingleNode("response/url0/in_database").InnerText; //Throw Null reference error here

这是xml:

<?xml version="1.0" encoding="utf-8"?>
<response>
    <meta>
        <timestamp>2016-04-20T13:14:43+00:00</timestamp>
        <serverid>dc985c81</serverid>
        <requestid>146.112.225.21.571780c3bb0213.81015830</requestid>
    </meta>
    <results>
        <url0>
            <url><![CDATA[http://stackoverflow.com/questions/18250671/how-to-read-single-node-value-from-xml-file]]></url>
            <in_database>false</in_database>
        </url0>
    </results>
</response>

我正在尝试获取url0节点值

1 个答案:

答案 0 :(得分:0)

你需要这样做:

XmlDocument xml = new XmlDocument();

        xml.LoadXml("<response>" +
                        "<meta>" +
                            "<timestamp>2016-04-20T13:14:43+00:00</timestamp>" +
                            "<serverid>dc985c81</serverid>" +
                            "<requestid>146.112.225.21.571780c3bb0213.81015830</requestid>" +
                        "</meta>" +
                        "<results>" +
                            "<url0>" +
                                "<url>someurl</url>" +
                                "<in_database>false</in_database>" +
                            "</url0>" +
                        "</results>" +
                    "</response>");

        var status = xml.DocumentElement.SelectSingleNode("/response/results/url0/in_database").InnerText; 
  

你在路径的开头错过了“/”:/ response / result ...