Windows phone 7 使用Linq解析XML时,序列不包含任何元素
我有这样一个XML:Windows phone 7 使用Linq解析XML时,序列不包含任何元素,windows-phone-7,xml-serialization,Windows Phone 7,Xml Serialization,我有这样一个XML: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSc
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<SampleResponse xmlns="http://tempuri.org/">
<SampleResult>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<NewDataSet xmlns="">
<Table diffgr:id="Table1" msdata:rowOrder="0">
<tag1>tag1 text</tag1>
<tag2>tag2 text</tag2>
</Table>
<Table diffgr:id="Table2" msdata:rowOrder="1">
<tag1>tag1 text</tag1>
<tag2>tag2 text</tag2>
</Table>
</NewDataSet>
</diffgr:diffgram>
</SampleResult>
</SampleResponse>
</soap:Body>
</soap:Envelope>
我的解析代码是:
string XMLresponse = e.response;
var XResult = XElement.Parse(XMLresponse);
var result = XResult.Descendants("Table").Select(t => new ParseClass
{
tag1 = t.Descendants("tag1").First().Value,
tag2 = t.Descendants("tag2").First().Value,
});
foreach (var res in result1)
{
string str=res.tag1;
str=res.tag2;
}
如果所有的标记都出现了,我就能够成功地解析上面的XML。但有时我的响应XML缺少名为tag2的标记,当时我无法解析XML,并出现异常,如“序列不包含元素”
我的要求是:
我尝试了FirstOrDefault方法来代替First方法,但没有用。
如果XML中缺少任何标记,则该对象的变量应为Null(即:如果缺少tag2,则res.tag2应为Null)。如何实现这一点?而不是使用
tag1 = t.Descendants("tag1").First().Value
使用
(tag2也是如此。)
FirstOrDefault()
如果值不存在,将返回null
,当要求转换空引用或文本内容时,XElement
到字符串的转换将返回null。完美答案Jon,感谢您的快速回复Jon。实际上,我正在尝试使用(string)t.subjections(“tag1”).FirstOrDefault().Value,但它不起作用。@AvinashReddy:是的,这将失败-因为将对空引用调用.Value
属性。
tag1 = t.Descendants("tag1").First().Value
tag1 = (string) t.Descendants("tag1").FirstOrDefault()