我在使用XPath读取xml节点值时遇到XPathException?
代码段:
XPathNavigator nav;
XPathDocument docNav;
string sampleXML = @"C:\\sample.xml";
string ThumbnailXpath = @"//ern:NewReleaseMessage/media/asset/thumbnailURL/text()";
docNav = new XPathDocument(sampleXML);
nav = docNav.CreateNavigator();
thumbnailURL = nav.SelectSingleNode(ThumbnailXpath).Value;
XML
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<ern:NewReleaseMessage xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xmlns:ern="http://ddex.net/xml/ern/37" ReleaseProfileVersionId="CommonReleaseTypes/12/AudioAlbum" LanguageAndScriptCode="en" xs:schemaLocation="http://ddex.net/xml/ern/37 http://ddex.net/xml/ern/37/release-notification.xsd" MessageSchemaVersionId="ern/37">
<IsBackfill>false</IsBackfill>
<media>
<asset id="050087105471">
<language>en_uk</language>
<grid/>
<cpCode/>
<firstReleaseDate/>
<territory/>
<thumbnailURL>placeholder</thumbnailURL>
<size/>
<description/>
</asset>
</media>
</ern:NewReleaseMessage>
异常
System.Xml中发生了未处理的“System.Xml.XPath.XPathException”类型异常。
其他信息:需要命名空间管理器或XsltContext。此查询具有前缀,变量或用户定义的函数。
答案 0 :(得分:3)
就像错误所说的那样,如果XPath使用命名空间,则需要使用命名空间管理器:
XPathNavigator nav;
XPathDocument docNav;
string sampleXML = @"C:\\sample.xml";
string ThumbnailXpath = @"//ern:NewReleaseMessage/media/asset/thumbnailURL/text()";
XmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable());
nsm.AddNamespace("ern", "http://ddex.net/xml/ern/37");
docNav = new XPathDocument(sampleXML);
nav = docNav.CreateNavigator();
thumbnailURL = nav.SelectSingleNode(ThumbnailXpath, nsm).Value;