开发者

Select specific xml node from xmlDocument then change xml node's attribute

开发者 https://www.devze.com 2023-01-15 09:18 出处:网络
I have a simple xml node inside an xml document in C# that I would like to query, then set the value for the visible attribute to false. Below is the xml. I need to be able to select the node by the n

I have a simple xml node inside an xml document in C# that I would like to query, then set the value for the visible attribute to false. Below is the xml. I need to be able to select the node by the node name(DGField) and the text_id(Test.ChangeRank). Does anyone know how to do this? Thanks in advance.

<DGField text_id="开发者_开发百科Test.ChangeRank" template="Ranking" visible="true">


Assuming your XmlDocument is called doc, then the following should work.

  XmlNode node = doc.SelectSingleNode("//DGField[@text_id='Test.ChangeRank']");
  if (node != null)
  {
    node.Attributes["visible"].Value = "false";
  }

This could do with more error checking to ensure the attribute being changed exists etc. but this keeps it clean.

Basically the first line uses an XPath expression to locate a DGField element where text_id='Test.ChangeRank'. If found then node is returned and then used to manipulate the desired attribute value.

I used the '//' syntax in the XPath query so that the entire Xml document is searched, this is not optimal, being more specific with the XPath can perform better. For example if you had a complete document that looked something like this

<root>
  <DGFields>
    <DGField text_id='1' template='Ranking' visible='true' />
    <DGField text_id='Test.ChangeRank' template='Ranking' visible='true' />
  </DGFields>
</root>

Then a more specific XPath query can be used like the following

XmlNode node = doc.SelectSingleNode(
  "root/DGFields/DGField[@text_id='Test.ChangeRank']");


There are various ways for doing this. I would think using XmlDocument and Regex are the best options.

Here is the XML approach:

        XmlDocument xdoc = new XmlDocument();
        xdoc.Load(@"c:\myxml.xml");
        XmlNode xn = xdoc.SelectSingleNode("//DGField[@text_id='Test.ChangeRank']");
        xn.Attributes["visible"].Value = "false";
0

精彩评论

暂无评论...
验证码 换一张
取 消