问题用C#来获得特定的XML元素的值 [英] issue to get specific XML element value using C#

查看:114
本文介绍了问题用C#来获得特定的XML元素的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下的XML文档,如何获得一个元素值:名称(在我的示例中,值是周六100)?我的困惑是如何处理的名字空间。谢谢你。

Suppose I have the following XML document, how to get the element value for a:name (in my sample, the value is Saturday 100)? My confusion is how to deal with the name space. Thanks.

我使用C#和VSTS 2008。

I am using C# and VSTS 2008.

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <PollResponse xmlns="http://tempuri.org/">
       <PollResult xmlns:a="http://schemas.datacontract.org/2004/07/FOO.WCF" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
          <a:name>Saturday 100</a:name>
       </PollResult>
    </PollResponse>
  </s:Body>
</s:Envelope>

在此先感谢, 乔治

thanks in advance, George

推荐答案

这是更容易,如果您使用的LINQ to XML类。否则,命名空间真的是烦人。

It's easier if you use the LINQ to XML classes. Otherwise namespaces really are annoying.

XNamespace ns = "http://schemas.datacontract.org/2004/07/FOO.WCF";
var doc = XDocument.Load("C:\\test.xml"); 
Console.Write(doc.Descendants(ns + "name").First().Value);

编辑。使用2.0

Edit. Using 2.0

XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("a", "http://schemas.datacontract.org/2004/07/FOO.WCF");
Console.Write(doc.SelectSingleNode("//a:name", ns).InnerText);

这篇关于问题用C#来获得特定的XML元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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