【问题标题】:xml XElement showing null pointer exceptionxml XElement 显示空指针异常
【发布时间】:2018-12-17 21:26:34
【问题描述】:

我在这方面遇到了最糟糕的情况,因为我通常不处理 XML 文档。

我有一长串已进入循环的 XML XNode,我需要将节点的一个特定元素存储在一个数组中。

但问题是,我经常遇到 NullPointerException 并且我正在画一个空白。

我的代码:

    Console.WriteLine("Items found: " + doc.Root.Nodes().Count());


        foreach (XNode node in doc.Root.Nodes())
        {
            XElement betternode = XElement.Parse(node.ToString());
            Console.WriteLine(betternode.Element("loc").Value); //Null Exception here
        }

计数显示文档中有 24,000 个节点。节点显示在本地,当我将节点内容复制到 W3 验证器时,它说 XML 格式正确。

节点如下所示:

    <url xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <loc>http://url.to/my.jpg</loc>
  <image:image xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
    <image:loc>http://url.to/my.jpg</image:loc>
    <image:title>Huge spider</image:title>
    <image:caption></image:caption>
  </image:image>
</url>

所以,既然我知道节点在那里并且有效,

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    &lt;url&gt; 元素定义了默认命名空间“http://www.sitemaps.org/schemas/sitemap/0.9”。所以在访问loc元素的时候需要用到它。

    你需要这样的东西

    XNamespace x = "http://www.sitemaps.org/schemas/sitemap/0.9";
    betternode.Element(x + "loc").Value
    

    另一种方式:

    XNamespace x = "http://www.sitemaps.org/schemas/sitemap/0.9";
    var locations = doc.Descendants(x + "loc");
    foreach (var loc in locations) { ... }
    

    【讨论】:

    • 我已经阅读了 3 个小时的文档,但我什至不知道这意味着什么。
    • 如果你只需要loc 元素。你可以考虑使用xpath?
    • 同样不需要重新解析节点。
    • @RichardSchneider,谢谢。我不确定为什么会这样,但确实如此,所以回到我的相关文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多