我正在尝试从 XML 中获取数据。我所知道的是,当我试图查找的动物不在 XML 数据中时,我总是会收到错误消息。示例如图所示。
这是存储在 XML 中的数据:
<?xml version="1.0" encoding="utf-8" ?>
<Root>
<Animal value="Elephant" size="2" name="Bob">
<Action age="1" size="1">I am small</Action>
<Action age="2" size="1">I am growing up</Action>
<Action age="3" size="1">I'm 3 years old</Action>
<Action age="4" size="1">I'm BIG</Action>
</Animal>
</Root>
这是 C# 编码的一部分:
XmlDocument xDoc = new XmlDocument();
xDoc.Load("animals.xml");
string animal = "Elephant";
MessageBox.Show(Convert.ToString(xDoc.SelectSingleNode("/Root/Animal[@value='" + animal + "']")
.Attributes["name"].InnerText));
当我更改时出现错误
string animal = "Tiger";
数据不存在如何解决?
最佳答案
您可以使用 Linq to Xml 获取动物的名称(如果未找到动物,它将返回 null
):
XDocument xdoc = XDocument.Load("animals.xml");
string animal = "Elephant";
var name = xdoc.Root.Elements()
.Where(a => (string)a.Attribute("value") == animal)
.Select(a => (string)a.Attribute("name"))
.FirstOrDefault();
您还可以简单地检查是否找到了与您的值匹配的动物,并且只有在匹配时才获取名称:
var xpath = String.Format("Root/Animal[@value='{0}']", animal);
var animalElement = xdoc.XPathSelectElement(xpath);
if (animalElement != null)
MessageBox.Show((string)animalElement.Attribute("name"));
关于c# - 如何检查 XML 值是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17771317/