简体   繁体   English

从xml元素获取值导致异常

[英]Getting value from xml element resulting in exception

I want to get the success value from the xml below: 我想从下面的xml中获取成功值:

<PIEngineResponse xmlns="http://www.pervasive.com/">
  <success>TRUE</success>
  <proxyId>10.10.90.15_test_user{3312564C-6A06-533B-52F0-C8F97C413137}</proxyId>
  <engineName>PIEngineController_Engine_245</engineName>
  <response>
    <NOSDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:NOSDocument" xsi:schemaLocation="NewNosXML.xsd">

If I use xpath, I get: 如果使用xpath,则会得到:

/tns:PIEngineResponse/tns:success 

Which causes the error: 导致错误的原因:

Namespace Manager or XsltContext needed. 需要名称空间管理器或XsltContext。 This query has a prefix, variable, or user-defined function. 该查询具有前缀,变量或用户定义的函数。

What can I do to get the success value to avoid this error? 我该怎么做才能获得成功值以避免此错误? Or how could I avoid the original error? 或者如何避免原始错误?

EDIT: Still no luck with code as: 编辑:仍然没有运气与代码为:

using (TextReader r1 = File.OpenText(localFilePath))
{

    XmlReader r = XmlReader.Create(r1);
    XDocument doc = XDocument.Load(r1, LoadOptions.None);
    XNamespace ns = "http://www.pervasive.com/";
    string successValue = (string) doc.Root.Element(ns + "success");
}

ignore naming conventions for now. 现在暂时忽略命名约定。

I would personally use LINQ to XML to get it to start with: 我将亲自使用LINQ to XML来开始它:

XDocument doc = ...;
XNamespace ns = "http://www.pervasive.com/";
string successValue = (string) doc.Root.Element(ns + "success");

If you really want to use XPath, you need a namespace manager (or an XsltContext , but it doesn't sound like you're using XSLT), just as the exception suggests - see this answer for an example. 如果您确实要使用XPath,则需要一个名称空间管理器(或XsltContext ,但这听起来并不像您在使用XSLT),就像例外所暗示的那样-请参见此答案作为示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM