如何检查Windows Phone中是否存在XMLNode
本文关键字:Phone 是否 存在 XMLNode Windows 何检查 检查 | 更新日期: 2023-09-27 18:10:21
我正在编写Windows Phone 8应用程序,我从web服务中获取XML数据,在一些响应中,在我的XML文档中,我获得了一些"标签",而在其他响应中,我没有获得这些标签,所以我如何检查XNode是否存在?请看下面我的XML文档:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Group>
<Id>205647</Id>
<Name>Docs</Name>
</Group>
<Group>
<Id>205648</Id>
<Name>Photos</Name>
</Group>
</root>
现在,在上面的文档中,后代"GROUP"在一些结果中存在,而在其他结果中不存在,我如何检查?
创建一个这样的扩展方法:
public static string TryGetElementValue(this XElement parentEl, string elementName, string defaultValue = null)
{
var foundEl = parentEl.Element(elementName);
if(foundEl != null)
{
return foundEl.Value;
}
else
{
return defaultValue;
}
}
这种方法允许您通过隔离元素存在的检查来保持代码的整洁。它还允许您定义一个默认值,这可能很有帮助
您可以遍历具有XmlTextReader
的所有节点并查找特定的XmlNode
Name。
用你的xml试试这个片段:
XmlDocument doc = new XmlDocument();
doc.Load("your.xml");
//Select the book node with the matching attribute value.
XmlNode nodeToFind;
XmlElement root = doc.DocumentElement;
// Selects all the title elements that have an attribute named group
nodeToFind = root.SelectSingleNode("//title[@group]");
if( nodeToFind != null )
{
// It was found, manipulate it.
}
else
{
// It was not found.
}
也看看这个。更新Windows Phone中已有的xml文件
希望有帮助!