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.

  1. Homo and machine-readable format.
  2. Information technology is platform independent.
  3. Its self-documenting format describes the structure and field names as well as specific values.
  4. XML is heavily used to shop the data and share the information.
  5. 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.
  6. 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.

  1. Add node/XML value to the existing XML.
  2. Edit/Update XML information.
  3. Remove the nod e from XML data.
  4. Select the node value from XML.
  5. 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:

  1. string  tempXml = @"<Projects>
  2. <Project ID='one'  Proper noun= 'project1'  />
  3. <Project ID='two'  Proper noun= 'project2'  />
  4. <Projection ID='3'  Name= 'project3'  />
  5. <Project ID='4'  Name= 'project4'  />
  6. <Projection ID='5'  Proper noun= 'project5'  />
  7. </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

  1. // Option1: Using InsertAfter()
  2. XmlDocument doc3 =new  XmlDocument();
  3. doc3.LoadXml(tempXml);
  4. XmlNode root1 = doc3.DocumentElement;
  5. XmlElement elem = doc3.CreateElement("Project" );
  6. XmlAttribute attr = doc3.CreateAttribute("ID" );
  7. attr.Value ="vi" ;
  8. elem.Attributes.Append(attr);
  9. XmlAttribute attr2 = doc3.CreateAttribute("Name" );
  10. attr2.Value ="Project6" ;
  11. elem.Attributes.Append(attr2);
  12. root1.InsertAfter(elem, root1.LastChild);
  13. doc3.Relieve(Console.Out);
  14. Console.WriteLine();

  15. // Option2: Using AppendChild()
  16. XmlDocument doc4 =new  XmlDocument();
  17. doc4.LoadXml(tempXml);
  18. XmlElement XEle = doc4.CreateElement("Projection" );
  19. XEle.SetAttribute("Name" , "Project6" );
  20. XEle.SetAttribute("ID" , "half-dozen" );
  21. doc4.DocumentElement.AppendChild(XEle.Clone());
  22. doc4.Salvage(Console.Out);
  23. Console.WriteLine();

Figure two : Output later adding new node

Using XDocument

  1. // Option1: Using AddAfterSelf ()
  2. XDocument xdoc = XDocument.Parse(tempXml);
  3. var cust = xdoc.Descendants("Project" )
  4.                 .Starting time(rec => rec.Aspect("ID" ).Value == "five" );
  5. cust.AddAfterSelf(new  XElement( "Project" , new  XAttribute( "ID" , "six" )));
  6. xdoc.Salve(Console.Out);
  7. Panel.WriteLine();

  8. // Option2: Using Add() method
  9. XDocument doc = XDocument.Parse(tempXml);
  10. XElement root =new  XElement( "Project" );
  11. root.Add together(new  XAttribute( "ID" , "6" ));
  12. root.Add together(new  XAttribute( "Proper name" , "Project6" ));
  13. doc.Element("Projects" ).Add together(root);
  14. doc.Save(Console.Out);
  15. Console.WriteLine();
  16. string  tempXmlNamespace = @"<Projects xmlns= 'http://schemas.microsoft.com/developer/msbuild/2003' >
  17.                     <Project ID='1'  Name= 'project1'  />
  18.                     <Project ID='ii'  Name= 'project2'  />
  19.                     <Project ID='3'  Name= 'project3'  />
  20.                     <Project ID='4'  Name= 'project4'  />
  21.                     <Project ID='v'  Proper noun= 'project5'  />
  22.                     </Projects>";
  23. XNamespace ns ="http://schemas.microsoft.com/programmer/msbuild/2003" ;
  24. XDocument xDoc = XDocument.Parse(tempXmlNamespace);
  25. var b = xDoc.Descendants(ns +"Project" ).Last();
  26. b.Parent.Add together(
  27. new  XElement(ns + "Project" ,
  28. new  XAttribute( "ID" , "6" ), new  XAttribute( "Name" , "Project6" )
  29.     )
  30. );
  31. xDoc.Save(Console.Out);
  32. 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

  1. // Option1: Using SetAttributeValue()
  2. XDocument xmlDoc = XDocument.Parse(tempXml);
  3. var items = from itemin  xmlDoc.Descendants( "Project" )
  4.             where item.Attribute("ID" ).Value == "ii"
  5.             select detail;
  6. foreach  (XElement itemElement in  items)
  7. {
  8.     itemElement.SetAttributeValue("Name" , "Project2_Update" );
  9. }
  10. xmlDoc.Save(Panel.Out);
  11. Console.WriteLine();
  12. // Option2: Using Aspect.Value()
  13. var doc = XElement.Parse(tempXml);
  14. var target = dr..Elements("Project" )
  15.         .Where(due east => e.Attribute("ID" ).Value == "2" )
  16.         .Single();
  17. target.Aspect("Name" ).Value = "Project2_Update" ;
  18. doc.Salve(Console.Out);
  19. Console.WriteLine();
  20. // Option3: Using ReplaceWith()
  21. XDocument xmlDoc1 = XDocument.Parse(tempXml);
  22. XElement xObj = xmlDoc1.Root.Descendants("Project" ).FirstOrDefault();
  23. xObj.ReplaceWith(new  XElement( "Project" , new  XAttribute( "ID" , "1" ),
  24. new  XAttribute( "Name" , "Project1_Update" )));
  25. xmlDoc1.Save(Console.Out);
  26. Console.WriteLine();

Effigy 3: Update XML Node value

Using XmlDocument

  1. int  nodeId = 2;
  2. XmlDocument xmlDoc2 =new  XmlDocument();
  3. xmlDoc2.LoadXml(tempXml);
  4. XmlNode node = xmlDoc2.SelectSingleNode("/Projects/Project[@ID="  + nodeId + "]" );
  5. node.Attributes["Proper name" ].Value = "Project2_Update" ;
  6. xmlDoc1.Save(Console.Out);
  7. 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

  1. // Option1: Remove using SelectSingleNode()
  2. int  nodeId = 1;
  3. XmlDocument xmlDoc =new  XmlDocument();
  4. xmlDoc.LoadXml(tempXml);
  5. XmlNode nodeToDelete = xmlDoc.SelectSingleNode("/Projects/Project[@ID="  + nodeId + "]" );
  6. if  (nodeToDelete != zero )
  7. {
  8.     nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
  9. }
  10. xmlDoc.Save(Console.Out);
  11. Console.WriteLine();
  12. XmlDocument doc2 =new  XmlDocument();
  13. doc2.Load(@"D:\ConsoleApplication4\MyData.xml" );
  14. XmlNodeList nodes = doc2.GetElementsByTagName("Project" );
  15. XmlNode node = nodes[0];
  16. node.ParentNode.RemoveChild(node);
  17. doc2.Save(Panel.Out);
  18. Console.WriteLine();
  19. XmlDocument doc1 =new  XmlDocument();
  20. doc1.LoadXml("<book genre='novel' ISBN='one-2-3'>"  +
  21. "<title>XML Manipulation</championship>"  +
  22. "</book>" );
  23. XmlNode root = doc1.DocumentElement;
  24. root.RemoveChild(root.FirstChild);
  25. doc1.Relieve(Panel.Out);
  26. Console.WriteLine();

Figure 4: Output after delete node

Using XDocument Class

  1. XDocument xdoc1 = XDocument.Parse(tempXml);
  2. var elementsToRemove = from elemetin  xdoc1.Elements( "Projects" ).Elements( "Projection" )
  3.                         where elemet.Attribute("Proper noun" ).Value == "project1"
  4.                         select elemet;
  5. foreach  (var e in  elementsToRemove)
  6. {
  7.     due east.Remove();
  8. }
  9. XDocument doc = XDocument.Load(@"D:\ConsoleApplication4\MyData.xml" );
  10. doc.Descendants("Project" ).Where(rec => rec.Attribute( "Proper noun" ).Value == "project2" ).Remove();
  11. doc.Salve(Console.Out);
  12. Console.WriteLine();
  13. XDocument xdoc = XDocument.Parse(tempXml);
  14. xdoc.XPathSelectElement("Projects/Project[@Name = 'project1']" ).Remove();
  15. xdoc.Salve(Console.Out);
  16. Console.WriteLine();
  17. XElement root2 = XElement.Parse(@"<Root>
  18.                     <Child1>
  19.                         <GrandChild1/>
  20.                         <GrandChild2/>
  21.                     </Child1>
  22.                     <Child2>
  23.                         <GrandChild3/>
  24.                         <GrandChild4/>
  25.                     </Child2>
  26.                 </Root>");
  27. root2.Chemical element("Child1" ).Element( "GrandChild1" ).Remove();
  28. root2.Chemical element("Child2" ).Elements().Remove();
  29. root2.Save(Console.Out);
  30. 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).

  1. XmlDocument xmldoc =new  XmlDocument();
  2. xmldoc.LoadXml(tempXml);
  3. int  nodeId = ii;
  4. XmlNode nodeObj = xmldoc.SelectSingleNode("/Projects/Project[@ID="  + nodeId + "]" );
  5. string  pName = nodeObj.Attributes[ "Name" ].Value;
  6. XmlNodeList xnList = xmldoc.SelectNodes("/Projects/Project" );
  7. foreach  (XmlNode xn in  xnList)
  8. {
  9. string  projectName = xn.Attributes[ "Name" ].Value;
  10. }
  11. XmlNodeList nodeList = xmldoc.GetElementsByTagName("Project" );
  12. foreach  (XmlNode node in  nodeList)
  13. {
  14.     var ID = node.Attributes["ID" ].Value;
  15.     var Proper noun = node.Attributes["Name" ].Value;
  16. }

Using XDocument

  1. string  tempXmlData = @"<Projects>
  2.                     <Project ID='ane'  Proper noun= 'project1'  />
  3.                     <Project ID='2'  Proper name= 'Not'  />
  4.                     <Projection ID='3'  Proper name= 'project3'  />
  5.                     <Project ID='four'  Name= 'Test'  />
  6.                     <Project ID='5'  Name= 'project5'  />
  7.                     </Projects>";
  8. XDocument medico = XDocument.Parse(tempXmlData);
  9. IEnumerable<Projection> upshot = from recin  doc.Descendants( "Project" )
  10.                                 where rec.Attribute("Name" ).Value.Contains( "projection" )
  11.                                 selectnew  Project()
  12.                                 {
  13.                                     ID = (int )rec.Attribute( "ID" ),
  14.                                     Proper name = (string )rec.Aspect( "Name" )
  15.                                 };
  16. foreach  (Project p in  result)
  17. {
  18.     Console.WriteLine("ID:"  + p.ID + ", Name: "  + p.Name);
  19. }

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.

  1. Listing<Projection> projects =new  List<Projection>()
  2. {
  3. new  Projection{ID = i, Proper noun= "Project1" },
  4. new  Projection{ID = 2, Name= "Project2" },
  5. new  Project{ID = 3, Proper name= "Project3" },
  6. new  Projection{ID = iv, Proper name= "Project4" },
  7. new  Project{ID = five, Proper name= "Project5" }
  8. };
  9. string  tempStr = SerializeObject<List<Project>>(projects);
  10. List<Projection> tempProjects = DeserializeObject<List<Project>>(tempStr);
  11. XDocument xDocument =new  XDocument(
  12. new  XDeclaration( "one.0" , "utf-8" , "yes" ),
  13. new  XComment( "LINQ To XML Demo" ),
  14. new  XElement( "Projects" ,
  15.     from projectin  projects
  16.     selectnew  XElement( "Project" , new  XAttribute( "ID" , project.ID),
  17. new  XAttribute( "Name" , project.Name))));
  18. xDocument.Save(Console.Out);
  19. 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.

  1. [XmlRoot( "Projects" )]
  2. public class  Project
  3. {
  4.     [XmlAttributeAttribute("ID" )]
  5. public int  ID { go ; set up ; }
  6.     [XmlAttributeAttribute("Name" )]
  7. public string  Name { get ; set ; }
  8. }

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.

  1. public static  T DeserializeObject<T>( string  xml)
  2. {
  3.     var serializer =new  XmlSerializer( typeof (T));
  4. using  (var tr = new  StringReader(xml))
  5.     {
  6. return  (T)serializer.Deserialize(tr);
  7.     }
  8. }
  9. public static cord  SerializeObject<T>(T obj)
  10. {
  11.     var serializer =new  XmlSerializer( typeof (T));
  12.     XmlWriterSettings settings =new  XmlWriterSettings();
  13.     settings.Encoding =new  UnicodeEncoding( truthful , true );
  14.     settings.Indent =true ;
  15.     XmlSerializerNamespaces ns =new  XmlSerializerNamespaces();
  16.     ns.Add("" , "" );
  17. using  (StringWriter textWriter = new  StringWriter())
  18.     {
  19. using  (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
  20.         {
  21.             serializer.Serialize(xmlWriter, obj, ns);
  22.         }
  23. render  textWriter.ToString();
  24.     }
  25. }

  26. 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.

ortegaanch1973.blogspot.com

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

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel