change attribute values froma xml file

Kran2022 381 Reputation points
2022-11-16T10:11:34.033+00:00

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"?>  
<PP>  
  <G N="Default">  
    <P N="QuickLabSetNetwork" V="False" />  
    <P N="QuickLabActivation" V="" />  
    <P N="QuickLabMode" V="1" />  
    <P N="QuickLabDirectory" V="True" />  
  </G>  
</PP  

Method 1:

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

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,647 questions
C#
C#
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.
10,097 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 110.7K Reputation points
    2022-11-16T10:22:14.857+00:00

    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