示例XML:
<Response xmlns="http://tempuri.org/">
<Result xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:string>18c03787-9222-4c9b-8f39-44c2b39c788e</a:string>
<a:string>774d38d2-a350-4711-8674-b69404283448</a:string>
</Result>
</Response>当我试图解析这段代码时,我将返回null,即:
XNamespace temp = "http://tempuri.org/";
XDocument xdoc = XDocument.Parse(xml);以下所有情况都返回null:
xdoc.Descendants(temp + "Result")
xdoc.Descendants();
xdoc.Element(temp + "Result");我误会什么了?
*编辑*
抱歉浪费了大家的时间。看来我使用的是http://www.tempuri.org而不是http://tempuri.org,并且在我的问题中错误地列出了正确的。
发布于 2015-02-05 21:05:45
下面是如何在几个明确的步骤中提取值:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace WaitForIt
{
class Program
{
static void Main(string[] args)
{
string thexml = @"<Response xmlns=""http://tempuri.org/""><Result xmlns:a=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><a:string>18c03787-9222-4c9b-8f39-44c2b39c788e</a:string><a:string>774d38d2-a350-4711-8674-b69404283448</a:string></Result></Response>";
XDocument doc = XDocument.Parse(thexml);
XNamespace ns = "http://tempuri.org/";
var result = doc.Descendants(ns + "Result");
var resultStrings = result.Elements();
foreach (var el in resultStrings)
{
Debug.WriteLine(el.Value);
}
// output:
// 18c03787-9222-4c9b-8f39-44c2b39c788e
// 774d38d2-a350-4711-8674-b69404283448
}
}
}https://stackoverflow.com/questions/28352918
复制相似问题