C# 使用C获取特定XML元素值的问题#
假设我有以下XML文档,如何获取:name的元素值(在我的示例中,值是100)?我的困惑是如何处理名称空间。谢谢 我正在使用C#和VSTS 2008C# 使用C获取特定XML元素值的问题#,c#,.net,xml,visual-studio-2008,C#,.net,Xml,Visual Studio 2008,假设我有以下XML文档,如何获取:name的元素值(在我的示例中,值是100)?我的困惑是如何处理名称空间。谢谢 我正在使用C#和VSTS 2008 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body> <PollResponse xmlns="http://tempuri.org/"> <PollResult xmlns:a="htt
<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>
星期六100
如果使用LINQ to XML类,会更容易。否则名称空间真的很烦人
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
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);
使用System.Xml.XmlTextReader类
System.Xml.XmlTextReader xr = new XmlTextReader(@"file.xml");
while (xr.Read())
{
if (xr.LocalName == "name" && xr.Prefix == "a")
{
xr.Read();
Console.WriteLine(xr.Value);
}
}
XPath是在2.0中获取XML文档位的直接方法
XmlDocument xml = new XmlDocument();
xml.Load("file.xml")
XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
manager.AddNamespace("a", "http://schemas.datacontract.org/2004/07/FOO.WCF");
string name = xml.SelectSingleNode("//a:name", manager).InnerText;
抱歉,我需要绑定到.Net 2.0。有什么解决方案吗?感谢adatapost,我更喜欢使用XPATH,因为它更稳定且易于维护,假设我将来可能会更改XML请求和响应的格式。