提问人:Sribin 提问时间:7/17/2023 最后编辑:marc_sSribin 更新时间:7/17/2023 访问量:50
如何修改嵌套 XML 中的内容
how to modify contents in a nested xml
问:
我需要将“C02”修改为“C02,C03”。如何实现这一点?我尝试了各种方法来修改XML内容,但到目前为止还没有找到解决方案。CompValue
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("XML value");
XmlNode root = xmlDoc.DocumentElement;
XmlNode myNode = root.SelectSingleNode("descendant::CompValue");
myNode.Value = "blabla";
也
root.SelectSingleNode("//CritGroup/Crit").InnerText = "NewValue";
这是我的示例xml
<Search Name="Test1" ProjTypeID="107">
<SearchType SearchTypeID="20246" />
<FiscalYear Year="2022" />
<CorpEnt CEID="367" CEName="Sample" />
<CritGroup CritGroupID="1" CritGroupAndOr="AND">
<Crit CritID="205" RelID="275" CompValue="C02" CompValueHuman="C02" AndOr="AND" TextBoxName="tbProjNum" />
<Crit CritID="208" RelID="280" CompValue="11" CompValueHuman="Yes" AndOr="AND" TextBoxName="" />
</CritGroup>
<PageSize Size="200" />
</Search>
答:
1赞
Krishna Varma
7/17/2023
#1
您需要获取完整的节点并替换属性。下面是示例
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
var critNode = xmlDoc.SelectSingleNode("//Crit[@CompValue='C02']");
if (critNode != null)
{
var compValueAttr = critNode.Attributes["CompValue"];
if (compValueAttr != null)
{
compValueAttr.Value = "C02,C03";
}
}
var modifiedXml = xmlDoc.OuterXml;
Console.WriteLine(modifiedXml);
评论
0赞
Sribin
7/17/2023
CompValue 的值并不总是“C02”
2赞
Yitzhak Khabinsky
7/17/2023
#2
请尝试以下解决方案。
它使用自 2007 年以来在 .Net Framework 中提供的 LINQ to XML API。
c#
void Main()
{
XDocument xdoc = XDocument.Parse(@"<Search Name='Test1' ProjTypeID='107'>
<SearchType SearchTypeID='20246'/>
<FiscalYear Year='2022'/>
<CorpEnt CEID='367' CEName='Sample'/>
<CritGroup CritGroupID='1' CritGroupAndOr='AND'>
<Crit CritID='205' RelID='275' CompValue='C02' CompValueHuman='C02'
AndOr='AND' TextBoxName='tbProjNum'/>
<Crit CritID='208' RelID='280' CompValue='11' CompValueHuman='Yes'
AndOr='AND' TextBoxName=''/>
</CritGroup>
<PageSize Size='200'/>
</Search>");
var Crits = xdoc.Descendants("Crit")
.Where(x => x.Attribute("CompValue").Value == "C02");
foreach (XElement Crit in Crits)
{
Crit.Attribute("CompValue").SetValue("C02,C03");
}
}
输出 XML
<Search Name="Test1" ProjTypeID="107">
<SearchType SearchTypeID="20246" />
<FiscalYear Year="2022" />
<CorpEnt CEID="367" CEName="Sample" />
<CritGroup CritGroupID="1" CritGroupAndOr="AND">
<Crit CritID="205" RelID="275" CompValue="C02,C03" CompValueHuman="C02" AndOr="AND" TextBoxName="tbProjNum" />
<Crit CritID="208" RelID="280" CompValue="11" CompValueHuman="Yes" AndOr="AND" TextBoxName="" />
</CritGroup>
<PageSize Size="200" />
</Search>
评论
System.Xml.Linq
innerText