读取 XML 时出现异常 - “需要命名空间管理器或 XsltContext”
本文关键字:命名空间 管理器 XsltContext XML 异常 读取 | 更新日期: 2023-09-27 18:31:16
我的xml如下
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="../../config/janes-deliver.xsl"?>
<!DOCTYPE janes:record SYSTEM "../../config/janesml-delivery-norm-2.1.dtd">
<janes:record xmlns:janes="http://dtd.janes.com/2002/Content/" id="j1891356689831320" pubabbrev="JIQ" sysId="JIQ0105" urname="record">
<janes:metadata xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="j1891356689831320" urname="metadata" xlink:type="simple">
<dc:rights xmlns:dc="http://purl.org/dc/elements/1.1/">Copyright © IHS Global Limited, 2014</dc:rights>
<dc:date xmlns:dc="http://purl.org/dc/elements/1.1/" qualifier="pubDate">30000101</dc:date>
<dc:date xmlns:dc="http://purl.org/dc/elements/1.1/" qualifier="postDate">20140822</dc:date>
<janes:title urname="title">IHS Jane's Navigating the Emerging Markets</janes:title>
<janes:shortTitle urname="shortTitle">Canada</janes:shortTitle>
<janes:sect1 id="j18967561358768718373" urname="sect1">
<janes:para id="j18967561358768718388" urname="para"><janes:link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="jiq0105_a.pdf" qualifier="pdf" urname="link" xlink:type="simple"><janes:linkText urname="linkText">Please click here for the full PDF report.</janes:linkText></janes:link></janes:para>
</janes:sect1>
<janes:sect1 id="j26330201380885096083" updated="y" urname="sect1">
<janes:title urname="title">Military inventories</janes:title>
.......................
我需要检索标签的内容
我写了如下代码
XmlDocument doc = new XmlDocument();
doc.Load(filepath);
foreach (XmlNode node in doc.SelectNodes("janes:link"))
{
string name = node.Name;
string value = node.InnerText;
// ...
}
我收到错误"需要命名空间管理器或 XsltContext。此查询具有前缀、变量或用户定义的函数。
有人可以帮忙吗?
试试这个:
XmlDocument doc = new XmlDocument();
doc.Load(filepath);
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("janes", "http://dtd.janes.com/2002/Content/");
foreach (XmlNode node in doc.SelectNodes(@"//janes:link", nsmgr))
{
//...
}
这个答案解释了为什么需要XmlNamespaceManager
。