gpt4 book ai didi

c# - 使用 XPath 读取 XML - 获取 XPathException

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:53 25 4
gpt4 key购买 nike

我在使用 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>

异常

An unhandled exception of type 'System.Xml.XPath.XPathException' occurred in System.Xml.

Additional information: Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.

最佳答案

就像错误所说的那样,如果您的 XPath 使用 namespace ,则需要使用 namespace 管理器:

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;

关于c# - 使用 XPath 读取 XML - 获取 XPathException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34177564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com