简体   繁体   中英

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

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM