我正在尝试使用 C# 和 xml,我正在尝试读取一个 XML 文件,我想验证“NumberOfDays”、“NumberOfBooks”、“NumberOfExam”、“CurrentDate”是否存在(如果缺失)。我想将它们添加到这些值中。
我有以下 xml 文档:
<?xml version="1.0" encoding="utf-8" ?>
<MySample>
<Content>
<add key="NumberOfDays" value="31" />
<add key="NumberOfBooks" value="20" />
<add key="NumberOfExam" value="6" />
<add key="CurrentDate" value="15 - Jul - 2011" />
</Content>
</MySample>
我正在使用 C# 编写一个示例应用程序
--------编辑--------
感谢您AresAvatar的回复。
但是如果该值存在,我想更新它的值,即如果让我们说
<add key="NumberOfExam" value="" />
我想将值更改为 6
最佳答案
您可以像这样获取存在哪些节点的列表:
// Get a list of which nodes exist
XmlDocument doc = new XmlDocument();
doc.LoadXml(myXml);
List<string> existingNodes = new List<string>();
XmlNodeList bookNodes = doc.SelectNodes("/MySample/Content/add");
foreach (XmlNode nextNode in bookNodes)
{
foreach (XmlAttribute nextAttr in nextNode.Attributes)
existingNodes.Add(nextAttr.InnerText);
}
您可以像这样添加缺失的节点:
// Add nodes
XmlNode addRoot = doc.SelectSingleNode("/MySample/Content");
XmlElement addme = doc.CreateElement("add");
addme.SetAttribute("NumberOfDays", "31");
addRoot.AppendChild(addme);
您可以像这样设置现有节点的值:
// Update a node
foreach (XmlNode nextNode in bookNodes)
{
foreach (XmlAttribute nextAttr in nextNode.Attributes)
{
switch (nextAttr.Name)
{
case "NumberOfDays":
((XmlElement)nextNode).SetAttribute("value", "31");
break;
// etc.
}
}
}
关于c# - 如何检查xml文档是否具有特定的属性列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6668523/