如何在XML中找到唯一元素并改变C#中的值?

时间:2017-10-12 08:44:33

标签: c# xml

我有一个大约有67K行的XML。 我不知道参数的确切值。 我只知道哪个<Section>包含所需的<Parameter>及其唯一名称。

XML看起来很相似:          

<Configurations>

<Configuration type="A">
<Configuration type="B">
<Configuration type="C">
<Section name="A">...</Section>
<Section name="B">...</Section>
<Section name="C">
<Parameter name="a" value="1" />
<Parameter name="specialStuff" value="this" />
</Section>
<Section name="D">...</Section>
...
</Configuration>
</Configuration>
</Configuration>
...

</Configurations>
</Document>

如何到达specialStuff参数并修改其值?

2 个答案:

答案 0 :(得分:1)

您可以使用XDocumentSetAttributeValue()

来实现这一目标
string xml = @"
             <Configurations>
                 <Configuration type=""A"">
                     <Configuration type=""B"" >
                         <Configuration type=""C"" >
                             <Section name=""A"" ></Section>
                             <Section name=""Bv"" ></Section>
                             <Section name= ""C"">
                                 <Parameter name= ""a"" value = ""1"" />
                                 <Parameter name= ""specialStuff"" value = ""this"" />
                             </Section>
                             <Section name= ""D"" ></Section>
                         </Configuration>
                     </Configuration>
                 </Configuration>
             </Configurations>";

XDocument xdoc = XDocument.Parse(xml);
xdoc.Descendants("Parameter")
    .Where(p => p.Attribute("name").Value == "specialStuff")
    .FirstOrDefault()?
    .SetAttributeValue("value", "youNewValue");

这会更改名为“参数”和value属性name的第一个匹配标记的specialStuff

方法Descendants()在xml中返回已过滤的元素集合(带文档顺序), 使用给定的标签名称。

如果您有Parametername个标签,specialStuff属性等于var specialStuffs = doc.Descendants("Parameter").Where(p => p.Attribute("name").Value == "specialStuff"); foreach (var item in specialStuffs) { item.SetAttributeValue("value", "newValue"); } ,则可以获取您的收藏,并单独修改:

select from_unixtime(1505143211)

答案 1 :(得分:1)

您可以使用XPath

XmlDocument doc = new XmlDocument();
doc.Load(@"D:\Yourxml.xml");

XmlElement root = doc.DocumentElement; 
string qry = "//Parameter[@name='specialStuff']"; 
XmlNode node = root.SelectSingleNode(qry);
node.Attributes["value"].Value = "newValue";

doc.Save(@"D:\Yourxml.xml");