1. Writing XML to the file
XmlDocument xmldoc =NewXmlDocument ();//building a DOM object in memoryXmlDeclaration XMLD = xmldoc.createxmldeclaration ("1.0","Utf-8","Yes");//Specifying document DeclarationsXmldoc.appendchild (XMLD);//Add a document description to the documentXmlElement rootelement= Xmldoc.createelement ("School");//Create a root element, schoolXmldoc.appendchild (rootelement);//Add the root element inXmlElement xmlclasselement= Xmldoc.createelement ("class");//add child elements to the root element (school)XmlAttribute attr = Xmldoc.createattribute ("ID");//Add a property id for class,attr. Value ="C01";//The value of ID is c01XmlClassElement.Attributes.Append (attr);//add an attribute to the class tag. Rootelement.appendchild (xmlclasselement);//add the class element to the school tagXmlElement xmlstudentelement= Xmldoc.createelement ("Student");//Create a student elementattr = Xmldoc.createattribute ("Sid");//to create a property called Sidattr. Value ="s011";//the value of the S011 property isXmlStudentElement.Attributes.Append (attr);//add an attribute to the elementXmlclasselement.appendchild (xmlstudentelement);//Add the student node to the class nodeXmlElement xmlnameelement= Xmldoc.createelement ("name"); Xmlnameelement.innertext="James"; XmlElement xmlageelement= Xmldoc.createelement (" Age"); Xmlageelement.innertext=" -"; Xmlstudentelement.appendchild (xmlnameelement); Xmlstudentelement.appendchild (xmlageelement); Xmldoc.save ("School.xml");//writes the DOM object to an XML filecompatible with. NET 2.0 versions
XDocument XDoc =NewXDocument ();//Create a DOM objectXdeclaration xdeclaration =NewXdeclaration ("1.0","Utf-8",NULL);//declaring document TypesXdoc.declaration = xdeclaration;//Add Document TypeXElement rootelement =NewXElement ("School");//Creating the root nodeXdoc.add (rootelement);//Add the school node to the documentXElement Xclass =NewXElement ("class");//create a class elementXclass.setattributevalue ("ID","C01");//add attributes and values to the class tag. Rootelement.add (Xclass); XElement Student=NewXElement ("Student"); Student. Setattributevalue ("ID","s001");//setting properties for student nodesStudent. Setelementvalue ("Name","Curry");//in the Student node, add the leaf node name with a value of curryStudent. Setelementvalue (" Age", -);//in the Student node, add the leaf node age, the value isStudent. Setelementvalue ("Sex","male");//in the Student node, add the leaf node sex with a value of maleXclass.add (student);//Add the student node to the class node. Xdoc.save ("Xuexiao.xml");//If the file does not exist, then one is created and the content is written. If the file exists, it will overwrite the content. 3.0 later versions
C # manipulating XML