我从一个看起来像这样的网站返回一个字符串
<?xml version=\"1.0\" encoding=\"UTF-8\"?><searchResponse requestID=\"500\" status=\"success\"><pso><psoID ID=\"61F2C644-F93A-11DE-8015-73A11AB14291\" targetID=\"mezeoAccount\"><data><email>sholobfc@bluefire.com.au</email><quotaMeg>2048</quotaMeg><quotaUsed>1879736</quotaUsed><active>true</active><unlocked>true</unlocked><allowPublic>true</allowPublic><realm>mezeo</realm><bandwidthQuota>1000000000</bandwidthQuota><billingDay>1</billingDay></data></psoID></pso></searchResponse>"
然后我尝试从中创建一个XDocument,以便我可以枚举元素
XDocument doc = new XDocument();
doc = XDocument.Parse(respStr);
但如果我每次都查询元素或后代,则返回null。我不能去
string s = doc.Element("email").Value;
// or
doc.Descendants("data"); // returns null as well
XDocument.Parse不会返回错误,但我似乎没有可搜索的xDocument。
任何人都可以看到我正在做的事情明显错误吗?
答案 0 :(得分:1)
在调用XDocument.Parse之前,您不需要创建新的XDocument。这不会造成任何问题,这是毫无意义的。
但是,这行是错误的,因为电子邮件不是文档根目录的子代:
doc.Element("email").Value;
你的第二个例子看起来不错。这对我有用:
string s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><searchResponse requestID=\"500\" status=\"success\"><pso><psoID ID=\"61F2C644-F93A-11DE-8015-73A11AB14291\" targetID=\"mezeoAccount\"><data><email>sholobfc@bluefire.com.au</email><quotaMeg>2048</quotaMeg><quotaUsed>1879736</quotaUsed><active>true</active><unlocked>true</unlocked><allowPublic>true</allowPublic><realm>mezeo</realm><bandwidthQuota>1000000000</bandwidthQuota><billingDay>1</billingDay></data></psoID></pso></searchResponse>";
XDocument doc = XDocument.Parse(s);
foreach (XElement e in doc.Descendants("data"))
Console.WriteLine(e);
结果:
<data>
<email>sholobfc@bluefire.com.au</email>
<quotaMeg>2048</quotaMeg>
<quotaUsed>1879736</quotaUsed>
<active>true</active>
<unlocked>true</unlocked>
<allowPublic>true</allowPublic>
<realm>mezeo</realm>
<bandwidthQuota>1000000000</bandwidthQuota>
<billingDay>1</billingDay>
</data>
回应你的第二个第三个问题(见这个答案的评论)试试这个:
using System;
using System.Xml.XPath;
using System.Xml.Linq;
class Program
{
public static void Main()
{
string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><searchResponse requestID=\"500\" status=\"success\"><pso><psoID ID=\"61F2C644-F93A-11DE-8015-73A11AB14291\" targetID=\"mezeoAccount\"><data><email>sholobfc@bluefire.com.au</email><quotaMeg>2048</quotaMeg><quotaUsed>1879736</quotaUsed><active>true</active><unlocked>true</unlocked><allowPublic>true</allowPublic><realm>mezeo</realm><bandwidthQuota>1000000000</bandwidthQuota><billingDay>1</billingDay></data></psoID></pso></searchResponse>";
XDocument doc = XDocument.Parse(xml);
foreach (XElement e in doc.XPathSelectElements("/searchResponse/pso/psoID/data/*"))
Console.WriteLine(e);
}
}
输出:
<email>sholobfc@bluefire.com.au</email>
<quotaMeg>2048</quotaMeg>
<quotaUsed>1879736</quotaUsed>
<active>true</active>
<unlocked>true</unlocked>
<allowPublic>true</allowPublic>
<realm>mezeo</realm>
<bandwidthQuota>1000000000</bandwidthQuota>
<billingDay>1</billingDay>