How Do I Read Node With Attriubvute C#
Introduction
XML stands for Extensible Markup Language file format, which is used to create common information formats and share both the format and the data on the Www, intranet, etc.
It has the advantages given below.
- Homo and machine-readable format.
- Information technology is platform independent.
- Its self-documenting format describes the structure and field names as well as specific values.
- XML is heavily used to shop the data and share the information.
- XML data is stored in text format. This makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing information.
- It strictly follows closing node, example-sensitive and node proper name.

In this commodity, we will discuss virtually XML manipulation in C#. We discuss the points given below.
- Add node/XML value to the existing XML.
- Edit/Update XML information.
- Remove the nod e from XML data.
- Select the node value from XML.
- XML Serialization.
Using lawmaking
We volition use by and large XDocument and XMLDocument class to manipulate XML data. The following is the LINQ to XML(XDocument) grade hierarchy, which will help to sympathize information technology more.

Add together node/xml value to existing XML
Below is the sample XML data, which we will utilise in our demonstration:
- string tempXml = @"<Projects>
- <Project ID='one' Proper noun= 'project1' />
- <Project ID='two' Proper noun= 'project2' />
- <Projection ID='3' Name= 'project3' />
- <Project ID='4' Name= 'project4' />
- <Projection ID='5' Proper noun= 'project5' />
- </Projects>";
In the sit-in, nosotros define how many different ways, where nosotros can add the node, using XMLDocument and XDocument class. The output is shown in Figure 2.
Using XmlDocument
- // Option1: Using InsertAfter()
- XmlDocument doc3 =new XmlDocument();
- doc3.LoadXml(tempXml);
- XmlNode root1 = doc3.DocumentElement;
- XmlElement elem = doc3.CreateElement("Project" );
- XmlAttribute attr = doc3.CreateAttribute("ID" );
- attr.Value ="vi" ;
- elem.Attributes.Append(attr);
- XmlAttribute attr2 = doc3.CreateAttribute("Name" );
- attr2.Value ="Project6" ;
- elem.Attributes.Append(attr2);
- root1.InsertAfter(elem, root1.LastChild);
- doc3.Relieve(Console.Out);
- Console.WriteLine();
-
- // Option2: Using AppendChild()
- XmlDocument doc4 =new XmlDocument();
- doc4.LoadXml(tempXml);
- XmlElement XEle = doc4.CreateElement("Projection" );
- XEle.SetAttribute("Name" , "Project6" );
- XEle.SetAttribute("ID" , "half-dozen" );
- doc4.DocumentElement.AppendChild(XEle.Clone());
- doc4.Salvage(Console.Out);
- Console.WriteLine();

Figure two : Output later adding new node
Using XDocument
- // Option1: Using AddAfterSelf ()
- XDocument xdoc = XDocument.Parse(tempXml);
- var cust = xdoc.Descendants("Project" )
- .Starting time(rec => rec.Aspect("ID" ).Value == "five" );
- cust.AddAfterSelf(new XElement( "Project" , new XAttribute( "ID" , "six" )));
- xdoc.Salve(Console.Out);
- Panel.WriteLine();
-
- // Option2: Using Add() method
- XDocument doc = XDocument.Parse(tempXml);
- XElement root =new XElement( "Project" );
- root.Add together(new XAttribute( "ID" , "6" ));
- root.Add together(new XAttribute( "Proper name" , "Project6" ));
- doc.Element("Projects" ).Add together(root);
- doc.Save(Console.Out);
- Console.WriteLine();
- string tempXmlNamespace = @"<Projects xmlns= 'http://schemas.microsoft.com/developer/msbuild/2003' >
- <Project ID='1' Name= 'project1' />
- <Project ID='ii' Name= 'project2' />
- <Project ID='3' Name= 'project3' />
- <Project ID='4' Name= 'project4' />
- <Project ID='v' Proper noun= 'project5' />
- </Projects>";
- XNamespace ns ="http://schemas.microsoft.com/programmer/msbuild/2003" ;
- XDocument xDoc = XDocument.Parse(tempXmlNamespace);
- var b = xDoc.Descendants(ns +"Project" ).Last();
- b.Parent.Add together(
- new XElement(ns + "Project" ,
- new XAttribute( "ID" , "6" ), new XAttribute( "Name" , "Project6" )
- )
- );
- xDoc.Save(Console.Out);
- Console.WriteLine();
Edit/U p engagement XML data
Sometimes, nosotros need to alter/update XML node value. For instance, we have a node for Projection,whose ID is 2 and want to update the Projection Name attribute. Post-obit code sample implements the same:
Using XDocument
- // Option1: Using SetAttributeValue()
- XDocument xmlDoc = XDocument.Parse(tempXml);
- var items = from itemin xmlDoc.Descendants( "Project" )
- where item.Attribute("ID" ).Value == "ii"
- select detail;
- foreach (XElement itemElement in items)
- {
- itemElement.SetAttributeValue("Name" , "Project2_Update" );
- }
- xmlDoc.Save(Panel.Out);
- Console.WriteLine();
- // Option2: Using Aspect.Value()
- var doc = XElement.Parse(tempXml);
- var target = dr..Elements("Project" )
- .Where(due east => e.Attribute("ID" ).Value == "2" )
- .Single();
- target.Aspect("Name" ).Value = "Project2_Update" ;
- doc.Salve(Console.Out);
- Console.WriteLine();
- // Option3: Using ReplaceWith()
- XDocument xmlDoc1 = XDocument.Parse(tempXml);
- XElement xObj = xmlDoc1.Root.Descendants("Project" ).FirstOrDefault();
- xObj.ReplaceWith(new XElement( "Project" , new XAttribute( "ID" , "1" ),
- new XAttribute( "Name" , "Project1_Update" )));
- xmlDoc1.Save(Console.Out);
- Console.WriteLine();

Effigy 3: Update XML Node value
Using XmlDocument
- int nodeId = 2;
- XmlDocument xmlDoc2 =new XmlDocument();
- xmlDoc2.LoadXml(tempXml);
- XmlNode node = xmlDoc2.SelectSingleNode("/Projects/Project[@ID=" + nodeId + "]" );
- node.Attributes["Proper name" ].Value = "Project2_Update" ;
- xmlDoc1.Save(Console.Out);
- Console.WriteLine();
Remove node from XML data
To remove the node from existing XML data, we will use XmlDocument and XDocument form.
Using XmlDocument Course
- // Option1: Remove using SelectSingleNode()
- int nodeId = 1;
- XmlDocument xmlDoc =new XmlDocument();
- xmlDoc.LoadXml(tempXml);
- XmlNode nodeToDelete = xmlDoc.SelectSingleNode("/Projects/Project[@ID=" + nodeId + "]" );
- if (nodeToDelete != zero )
- {
- nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
- }
- xmlDoc.Save(Console.Out);
- Console.WriteLine();
- XmlDocument doc2 =new XmlDocument();
- doc2.Load(@"D:\ConsoleApplication4\MyData.xml" );
- XmlNodeList nodes = doc2.GetElementsByTagName("Project" );
- XmlNode node = nodes[0];
- node.ParentNode.RemoveChild(node);
- doc2.Save(Panel.Out);
- Console.WriteLine();
- XmlDocument doc1 =new XmlDocument();
- doc1.LoadXml("<book genre='novel' ISBN='one-2-3'>" +
- "<title>XML Manipulation</championship>" +
- "</book>" );
- XmlNode root = doc1.DocumentElement;
- root.RemoveChild(root.FirstChild);
- doc1.Relieve(Panel.Out);
- Console.WriteLine();

Figure 4: Output after delete node
Using XDocument Class
- XDocument xdoc1 = XDocument.Parse(tempXml);
- var elementsToRemove = from elemetin xdoc1.Elements( "Projects" ).Elements( "Projection" )
- where elemet.Attribute("Proper noun" ).Value == "project1"
- select elemet;
- foreach (var e in elementsToRemove)
- {
- due east.Remove();
- }
- XDocument doc = XDocument.Load(@"D:\ConsoleApplication4\MyData.xml" );
- doc.Descendants("Project" ).Where(rec => rec.Attribute( "Proper noun" ).Value == "project2" ).Remove();
- doc.Salve(Console.Out);
- Console.WriteLine();
- XDocument xdoc = XDocument.Parse(tempXml);
- xdoc.XPathSelectElement("Projects/Project[@Name = 'project1']" ).Remove();
- xdoc.Salve(Console.Out);
- Console.WriteLine();
- XElement root2 = XElement.Parse(@"<Root>
- <Child1>
- <GrandChild1/>
- <GrandChild2/>
- </Child1>
- <Child2>
- <GrandChild3/>
- <GrandChild4/>
- </Child2>
- </Root>");
- root2.Chemical element("Child1" ).Element( "GrandChild1" ).Remove();
- root2.Chemical element("Child2" ).Elements().Remove();
- root2.Save(Console.Out);
- Console.WriteLine();
Select node value from XML
When nosotros employ XML information, nosotros want to fetch the data which is based on the node value. We need the projection name whose ID is two. We can use XMLDocument class or XDocument(System.XML.Linq namespace).
- XmlDocument xmldoc =new XmlDocument();
- xmldoc.LoadXml(tempXml);
- int nodeId = ii;
- XmlNode nodeObj = xmldoc.SelectSingleNode("/Projects/Project[@ID=" + nodeId + "]" );
- string pName = nodeObj.Attributes[ "Name" ].Value;
- XmlNodeList xnList = xmldoc.SelectNodes("/Projects/Project" );
- foreach (XmlNode xn in xnList)
- {
- string projectName = xn.Attributes[ "Name" ].Value;
- }
- XmlNodeList nodeList = xmldoc.GetElementsByTagName("Project" );
- foreach (XmlNode node in nodeList)
- {
- var ID = node.Attributes["ID" ].Value;
- var Proper noun = node.Attributes["Name" ].Value;
- }
Using XDocument
- string tempXmlData = @"<Projects>
- <Project ID='ane' Proper noun= 'project1' />
- <Project ID='2' Proper name= 'Not' />
- <Projection ID='3' Proper name= 'project3' />
- <Project ID='four' Name= 'Test' />
- <Project ID='5' Name= 'project5' />
- </Projects>";
- XDocument medico = XDocument.Parse(tempXmlData);
- IEnumerable<Projection> upshot = from recin doc.Descendants( "Project" )
- where rec.Attribute("Name" ).Value.Contains( "projection" )
- selectnew Project()
- {
- ID = (int )rec.Attribute( "ID" ),
- Proper name = (string )rec.Aspect( "Name" )
- };
- foreach (Project p in result)
- {
- Console.WriteLine("ID:" + p.ID + ", Name: " + p.Name);
- }

Figu re 5: Result later on utilize filter
We can generate XML data from C# objects. For instance, nosotros have a list of projects and we want it in XML format. The code sample is given below.
- Listing<Projection> projects =new List<Projection>()
- {
- new Projection{ID = i, Proper noun= "Project1" },
- new Projection{ID = 2, Name= "Project2" },
- new Project{ID = 3, Proper name= "Project3" },
- new Projection{ID = iv, Proper name= "Project4" },
- new Project{ID = five, Proper name= "Project5" }
- };
- string tempStr = SerializeObject<List<Project>>(projects);
- List<Projection> tempProjects = DeserializeObject<List<Project>>(tempStr);
- XDocument xDocument =new XDocument(
- new XDeclaration( "one.0" , "utf-8" , "yes" ),
- new XComment( "LINQ To XML Demo" ),
- new XElement( "Projects" ,
- from projectin projects
- selectnew XElement( "Project" , new XAttribute( "ID" , project.ID),
- new XAttribute( "Name" , project.Name))));
- xDocument.Save(Console.Out);
- Console.WriteLine();

Figu re half-dozen: Subsequently convert object to XML
XML Serialization/Deserialization
Serialization/Deserialization is a cool and important feature of an application. Information technology is required when your want to communicate/send data to other applications. Serialization is a process to convert an object to other formats like XML or binary. Deserialization is just reverse process of Serialization means to convert byte array or XML data to the objects.
The following points needs to retrieve when in that location is a class for serialization.
- XML serialization only serializes public fields and backdrop.
- XML serialization does non include any type information.
- We need to have a default/ non-parameterized constructor in gild to serialize an object.
- ReadOnly properties are non serialized.
Below are some important attributes while Serialization happens.
- XmlRoot Represents XML certificate'southward root Element
- XmlElement Field will be serialized as an XML element
- XmlAttribute Field volition be serialized as an XML aspect
- XmlIgnore F ield/property volition be ignore d during serialization
Let'southward design Projection entity for serialization.
- [XmlRoot( "Projects" )]
- public class Project
- {
- [XmlAttributeAttribute("ID" )]
- public int ID { go ; set up ; }
- [XmlAttributeAttribute("Name" )]
- public string Name { get ; set ; }
- }
After designing an entity, nosotros have DeserializationObject() method, which takes XML data parameter and returns object. Likewise, we have a method SerializeObject() which takes an object as a parameter and returns the data as XML format.
- public static T DeserializeObject<T>( string xml)
- {
- var serializer =new XmlSerializer( typeof (T));
- using (var tr = new StringReader(xml))
- {
- return (T)serializer.Deserialize(tr);
- }
- }
- public static cord SerializeObject<T>(T obj)
- {
- var serializer =new XmlSerializer( typeof (T));
- XmlWriterSettings settings =new XmlWriterSettings();
- settings.Encoding =new UnicodeEncoding( truthful , true );
- settings.Indent =true ;
- XmlSerializerNamespaces ns =new XmlSerializerNamespaces();
- ns.Add("" , "" );
- using (StringWriter textWriter = new StringWriter())
- {
- using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
- {
- serializer.Serialize(xmlWriter, obj, ns);
- }
- render textWriter.ToString();
- }
- }
-
- string tempStr = SerializeObject<List<Project>>(projects);
List<Project> tempProjects = DeserializeObject<List<Project>>(tempStr);

Figu re 7: Upshot after Serialization
XmlDocument vs XDocument
Nosotros generally used XmlDocument or XDocument class to manipulate XML data. Withal, there are some differences betwixt them:
- XDocument(Organisation.Xml.Linq) is from the LINQ to XML API and XmlDocument(System.Xml.XmlDocument) is the standard DOM-style API for XML.
- If you're using .NET version 3.0 or lower, you have to apply XmlDocument, the classic DOM API. On the other hand, if you are using .NET version 3.5 onwards, you need to use XDocument.
- Performance wise XDocument is faster than XmlDocument because information technology (XDocument) is newly adult to go amend usability with LINQ. It's (XDocument) much simpler to create documents and process them.
Conclusion
We learned how to employ LINQ to XML to manipulate XML by loading external XML files and reading the data within, too as the writing data to external XML files. We also discussed how to use XmlDocument and XDocument, as XDocument has more features. We demand to apply this if you are using .Internet framework 3.5 onwards.
Hope this helps.
Source: https://www.c-sharpcorner.com/article/xml-manipulation-in-c-sharp/
0 Response to "How Do I Read Node With Attriubvute C#"
Post a Comment