gpt4 book ai didi

c# - 如何在 C# 中使用 XmlDocument 和 XmlNode 修改现有的 XML 文件

转载 作者:IT王子 更新时间:2023-10-29 04:06:01 27 4
gpt4 key购买 nike

我已经实现了在应用程序初始化时使用 XmlTextWriter 创建下面的 XML 文件。

并且知道我不知道如何使用 XmlDocumentXmlNode 更新 childNode id 值。

是否有一些属性可以更新 id 值?我尝试了 InnerText 但失败了。谢谢。

<?xml version="1.0" encoding="UTF-8"?>
<Equipment xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<License licenseId="" licensePath=""/>
<DataCollections>
<GroupAIDs>
<AID id="100">
<Variable id="200"/>
<Variable id="201"/>
</AID>
<AID id="">
<Variable id="205"/>
</AID>
<AID id="102"/>
</GroupAIDs>
<GroupBIDs>
<BID id="2000">
<AID id="100"/>
</BID>
<BID id="2001">
<AID id="101"/>
<AID id="102"/>
</BID>
</GroupBIDs>
<GroupCIDs>
<BID id="8"/>
<BID id="9"/>
<BID id="10"/>
</GroupCIDs>
</DataCollections>
</Equipment>

最佳答案

你需要做这样的事情:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];

// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;

// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

关于c# - 如何在 C# 中使用 XmlDocument 和 XmlNode 修改现有的 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2558787/

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