• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 338
  • Last Modified:

Getting and setting attributes of XmlDocument

I have a config file that looks like the following:

      <app name=henry>
            <filter value=zxczxc>
                  <level value=TOP/>
      <app name=hank>
            <filter value=qweqwe>
                 <level value=BOTTOM/>

I want to be able to 'get' the attribute value for 'level' in the 'hank' section ONLY and I also
want to be able to set a new value for the same.

How can I accomplish this (code) using the XmlDocument and/or XmlElement classes?
1 Solution
Carl TawnSystems and Integration DeveloperCommented:
First of all your XML is badly formed. You need quotes around the attribute values. So your XML becomes:

          <app name="henry">
                <filter value="zxczxc">
                      <level value="TOP" />
          <app name="hank">
                <filter value="qweqwe">
                     <level value="BOTTOM" />

Assuming your XML is loaded into an XmlDocument named doc:

            // grab the level node belonging to app node with "henry"
            XmlNode app = doc.SelectSingleNode("/root/app[@name='henry']/filter/level");

            app.Attributes["value"].InnerText;                    // retrieve the value
            app.Attributes["value"].InnerText = "wibble";    // set the value
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Tackle projects and never again get stuck behind a technical roadblock.
Join Now