change attribute values froma xml file

Kran2022 406 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.

Developer technologies | Windows Presentation Foundation
Developer technologies | C#
Developer technologies | 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.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Viorel 126.3K 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

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.