The core class XElement of Linq To XML. An XElement represents a node, new XElement ("Order"), creates a label named "Order", and CALLS Add To Add subnodes, which is also an XElement object!
Below are some common forms of XML operations for LINQ.
/// Write the file (generate the node type)
?
XElement ePersons = new XElement( "Persons" ); XElement ptom = new XElement( "Person" ); // Add a Person Node ptom.Add( new XElement( "Name" , "Tom" )); // Add a subnode under ptom ptom.Add( new XElement( "Age" , "18" )); ePersons.Add(ptom); |
XElement pjack = new XElement("Person");
pjack.Add(new XElement("Name", "Jack"));
pjack.Add(new XElement("Age", "20"));
ePersons.Add(pjack);
Final generation:
<?xml version="1.0" encoding="utf-8" ?>
<Persons>
<Person>
<Name>Tom</Name>
<Age>18</Age>
</Person>
<Person>
<Name>Jack</Name>
<Age>20</Age>
</Person>
</Persons>
/// Write a file (generating attribute attributes)
?
XElement ptom = new XElement( "Person" ); ptom.Add( new XAttribute( "Name" , "tom" )); // Add XAttribute to generate attributes ptom.Add( new XAttribute( "Age" , "18" )); ePersons.Add(ptom); XElement pjack = new XElement( "Person" ); pjack.Add( new XAttribute( "Name" , "jack" )); pjack.Add( new XAttribute( "Age" , "20" )); ePersons.Add(pjack); |
Final generation:
<Persons>
<Person Name="tom" Age="18"/>
<Person Name="jack" Age="20"/>
</Persons>
// Read the value of the node format in XML format
?
XDocument xd= XDocument.Load( "XML file address" ); foreach (XElement item in xd.Root.Descendants( "Person" )) // Obtain the value of the Person node and its Name. { Console.WriteLine(item.Element( "Age" ).Value); // The Name Of The next node of the Person Node } Note: The doc. root (get the XElement object of the root node). XElement ("tagname") method returns the first node named tagname under the node. If doc. root. XElements (plural form) is to get all the child nodes, Descendants ( "“tagname”" ) Child node |
// Read the value of the attribute format in XML.
?
XDocument xd= XDocument.Load( @"D:\Program Files\Demo\Demo\ConsoleApplication2\XMLFile2.xml" ); foreach (XElement item in xd.Root.Descendants( "Person" )) // Obtain the value of the Person node and its Name. { Console.WriteLine(item.Attribute( "Age" ).Value); // The Name Of The next node of the Person Node } |