gpt4 book ai didi

c# - 如何检查 xml 文档是否具有特定的属性列表?

转载 作者:行者123 更新时间:2023-11-30 21:13:48 24 4
gpt4 key购买 nike

我正在尝试使用 C# 和 xml,我正在尝试读取一个 XML 文件,我想验证“NumberOfDays”、“NumberOfBooks”、“NumberOfExam”、“CurrentDate”是否存在(如果丢失)。我想用这些值添加它们。

我有以下 xmldocument:

<?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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com