使用 C# 在 XML 文档中查找特定值的好方法是什么? [英] What is a good way to find a specific value in an XML document using C#?

查看:15
本文介绍了使用 C# 在 XML 文档中查找特定值的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用一个由 Oracle 公开的 WebService,它接受 ItemID 的输入并返回给我相应的项目编号.我想从响应中包含的 XML 中获取已返回的项目编号.

I'm calling a WebService exposed by Oracle that accepts an input of an ItemID and returns to me the corresponding Item Number. I want to grab the Item Number that has been returned out of the XML contained in the response.

XML 如下所示:

<env:Envelope
  xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:ns0="http://dev1/MyWebService1.wsdl">
 <env:Header>
  <wsse:Security
    xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
    xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
    xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
    env:mustUnderstand="1"/>
 </env:Header>
 <env:Body>
  <ns0:getItemNbrByItemIdResponseElement>
   <ns0:result>1010603</ns0:result>
  </ns0:getItemNbrByItemIdResponseElement>
 </env:Body>
</env:Envelope>

我只想抓取 1010603,尤其是 1010603.

I'm interested in grabbing only the <ns0:result>1010603</ns0:result> particularly only the 1010603.

我没有做过很多使用 C# 解析 XML 的工作,到目前为止我正在尝试几种不同的方法.推荐的方法是什么?

I haven't done a lot of work parsing XML using C# and I'm playing around with a few different methods so far. What is the recommended way to do this?

我使用的是 VS2008(所以 XPath 可用等)

I'm on VS2008 (so XPath is available etc.)

推荐答案

我个人会使用 LINQ to XML,因为我发现它比 XPath 更容易处理,尤其是在涉及名称空间时.你会做这样的事情:

I'd personally use LINQ to XML, because I find that easier to deal with than XPath, particularly when namespaces are involved. You'd do something like:

XNamespace ns0 = "http://dev1/MyWebService1.wsdl";

String result = doc.Descendants(ns0 + "result").First().Value;

请注意,此处的 doc 应为 XDocument不是XmlDocument.(我的猜测是这就是它没有出现的原因.)

Note that doc here is expected to be an XDocument, not an XmlDocument. (My guess is that this is why it wasn't showing up for you.)

这篇关于使用 C# 在 XML 文档中查找特定值的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆