首页 > 解决方案 > xml XElement 显示空指针异常

问题描述

我在这方面遇到了最糟糕的情况,因为我通常不处理 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#xmllinq

解决方案


<url>元素定义了“ 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) { ... }

推荐阅读