c# - 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>
所以,既然我知道节点在那里并且有效,
解决方案
该<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) { ... }
推荐阅读
- javascript - 如何在本机反应中修复“.then 不是函数”
- html - 在列表视图中打开和关闭可展开按钮
- android - 我的 kotlin 代码出现问题...有人可以检查我的代码吗?
- javascript - 元素类型无效:应为字符串(用于内置组件)或类/函数(用于复合组件)
- angular - 角度材料表检索数据但不将其可视化
- sql - 此 SELECT 语句 (PLSQL) 中需要一个 INTO 子句
- python - Selenium 找不到 99% 的元素,为什么?
- python - Python 3.7.4 在 Windows 上是否缺少兼容性 EXE 文件?
- java - 我如何通过 lambda 创建字符串比较器?
- html - HTML & CSS Slide Out Navigation - 我做错了什么?