How to change XML Attribute

Mike; Everytime I need to modify an XML document I work it this way: //Here is the variable with which you assign a new value to the attribute string newValue = string.Empty; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlFile); XmlNode node = xmlDoc.SelectSingleNode(“Root/Node/Element”); node.Attributes[0].Value = newValue; xmlDoc.Save(xmlFile); //xmlFile is the path of your file to be … Read more

XDocument containing namespaces

Try this, works for me XNamespace nsSys = “http://schemas.microsoft.com/2004/06/windows/eventlog/system”; XElement xEl2 = xDoc.Element(nsSys + “System”); XElement xEl3 = xEl2.Element(nsSys + “Correlation”); XAttribute xAtt1 = xEl3.Attribute(“ActivityID”); String sValue = xAtt1.Value; You need to use Namespaces. Full source for trial public static void Main() { XElement xDoc = XElement.Parse( @”<E2ETraceEvent xmlns=””http://schemas.microsoft.com/2004/06/E2ETraceEvent””> <System xmlns=””http://schemas.microsoft.com/2004/06/windows/eventlog/system””> <EventID>589828</EventID> <Type>3</Type> <SubType Name=””Information””>0</SubType> … Read more

Use Linq to Xml with Xml namespaces

LINQ to XML methods like Descendants and Element take an XName as an argument. There is a conversion from string to XName that is happening automatically for you. You can fix this by adding an XNamespace before the strings in your Descendants and Element calls. Watch out because you have 2 different namespaces at work. … Read more

XDocument or XmlDocument

If you’re using .NET version 3.0 or lower, you have to use XmlDocument aka the classic DOM API. Likewise you’ll find there are some other APIs which will expect this. If you get the choice, however, I would thoroughly recommend using XDocument aka LINQ to XML. It’s much simpler to create documents and process them. … Read more

LINQ to read XML

Try this. using System.Xml.Linq; void Main() { StringBuilder result = new StringBuilder(); //Load xml XDocument xdoc = XDocument.Load(“data.xml”); //Run query var lv1s = from lv1 in xdoc.Descendants(“level1”) select new { Header = lv1.Attribute(“name”).Value, Children = lv1.Descendants(“level2″) }; //Loop through results foreach (var lv1 in lv1s){ result.AppendLine(lv1.Header); foreach(var lv2 in lv1.Children) result.AppendLine(” ” + lv2.Attribute(“name”).Value); } … Read more