tags:

views:

51

answers:

2

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">
+3  A: 

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']");
Chris Taylor
A: 

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