change attribute values froma xml file

Kran2022 381 Reputation points

Hi All:
From the below XML file, i tried to change the value of each attribute "V" from button click but i end having a null value for V by using below methods:

<?xml version="1.0" encoding="utf-8"?>  
  <G N="Default">  
    <P N="QuickLabSetNetwork" V="False" />  
    <P N="QuickLabActivation" V="" />  
    <P N="QuickLabMode" V="1" />  
    <P N="QuickLabDirectory" V="True" />  

Method 1:

 XmlDocument xmlDoc = new XmlDocument();  
XmlNode node = xmlDoc.SelectSingleNode("/PP/G/@N='QuickLabSetNetwork'/@V=''");  
 node.InnerText = "TTT";  

Method 2:

XElement xml = XElement.Load(filenametoread);  
            var lineItemXML = from x in xml.Descendants("PP")  
                              select x;  
            foreach (XElement xe in lineItemXML)  
                Console.WriteLine(string.Format("N={0}, V={1}"  
                    , xe.Element("G").Element("P").Element("N").Element("V").Value  

Thanks in advance for yor your help.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,367 questions
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,188 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 94,511 Reputation points

    For the shown sample file, try this fragment:

    XmlDocument xmlDoc = new XmlDocument( );  
    xmlDoc.Load( filenametoread );  
    XmlNode node = xmlDoc.SelectSingleNode( "/PP/G/P[@N='QuickLabActivation' and @V='']/@V" );  
    node.Value = "TTT";  
    xmlDoc.Save( filenametoread );  

    To change all of empty values:

    . . .  
    foreach( XmlNode node in xmlDoc.SelectNodes( "/PP/G/P/@V[.='']" ) )  
        node.Value = "TTT";  
    . . .  
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful