1. XML DOM Overview
XML documents are case sensitive, attributes are enclosed in quotes, and each tag must be closed.
DOM is a tree-like representation of an XML document in memory.
Inheritance relationship diagram:
XmlNode;//XML node......XmlDocument;//XML Documentation............XmlDataDocument;//Document related to Dataset......XmlDocumentFragment;// Document snippet......XmlLinkedNode;//Connect nodes (abstract class)............XmlDeclaration;//XML statement:............XmlDocumentType;//Document Type............XmlElement;//element............XmlEntityReference;//Entity reference node............XmlProcessingInstruction;//Processing instructions............XmlCharacterData;//Character data (abstract class)..................XmlCDataSection;//CDATA Festival..................XmlComment;//Note..................XmlSignificantWhitespace;//Effective blank..................XmlWhitespace;//blank..................XmlText;//Text content of element or attribute......XmlAttribute;//property......XmlEntity;//Entity Statement......XmlNotation;//Notation Statement
2. XML members
1. XMl node: XmlNode
1. Attributes:
- ChildNodes: All child nodes.
- FirstChild: The first child.
- HasChildNodes: Get whether there are any child nodes.
- LastChild: The last child node.
- ParentNode: Parent node (for nodes that can have parent).
- NextSibling: A sibling node immediately after this node.
- PreviousSibling: A sibling node immediately before this node.
- InnerText: Text values of a node and all its child nodes.
- InnerXml: XML tags for child nodes.
-
OuterXml: This node and all its child nodes XML tags.
- NodeType: Get the type of the current node.
- Value: The value of the node.
- Attributes: The node's properties XmlAttributeCollection.
- OwnerDocument: The XmlDocument to which the node belongs.
2. Method:
- AppendChild(XmlNode): Added to the end of the child node list of this node.
- PrependChild(XmlNode): Append to the beginning of the child node list of this node.
- InsertAfter(XmlNode, XmlNode): Insert the specified node immediately after the specified node.
-
InsertBefore(XmlNode, XmlNode): Insert the specified node immediately before inserting the specified node.
- RemoveAll() : Removes all child nodes and/or properties of the current node.
- RemoveChild(XmlNode): Removes the specified child node.
- ReplaceChild(XmlNode, XmlNode): Replace child node newChild with the oldChild node.
- SelectNodes(String): Select a list of nodes matching the XPath expression.
- SelectSingleNode(String): Select the first XmlNode that matches the XPath expression.
- WriteContentTo(XmlWriter): When rewritten in a derived class, all children of the node are saved to the specified XmlWriter.
- WriteTo(XmlWriter): When rewritten in the derived class, save the current node to the specified XmlWriter.
- Clone() : Create a copy of this node.
- CloneNode(Boolean): Creates a copy of the node when rewritten in the derived class
- CreateNavigator() : Create XPathNavigator to browse this object.
2. XML document: XMLDocument
1. Attributes:
- DocumentElement: Get the root of the document XmlElement.
- DocumentType: Get the node containing the DOCTYPE declaration.
- PreserveWhitespace : Gets or sets a value indicating whether to keep a blank area in the element content.
- Schemas : Gets or sets the XmlSchemaSet object associated with this XmlDocument.
- XmlResolver: Set up XmlResolver for parsing external resources.
2. Method:
- GetElementById(String): Gets the XmlElement with the specified ID.
- GetElementsByTagName(String): Returns an XmlNodeList that contains a list of all child elements that match the specified Name.
- ImportNode(XmlNode, Boolean): Imports a node from another document to the current document. Load(Stream) Loads the XML document from the specified stream.
- Load(String): Load the XML document from the specified URL. .
- LoadXml(String): Load the XML document from the specified string.
- Save(String): Save the XML document to the specified file. If the specified file exists, this method overwrites it.
- Validate(ValidationEventHandler): Verify that XmlDocument is the XML Schema Definition Language (XSD) schema contained in the Schemas property.
- ReadNode(XmlReader): Create an XmlNode object based on the information in XmlReader. The reader must be positioned on a node or property.
-
Create****(String): Creates Xml*** with the specified Name.
- CreateNavigator() : Creates a new XPathNavigator object to navigate this document.
3. Events:
- NodeChanging、NodeChanged:Occurs when the value of the node belonging to the document will be changed.
- NodeInserting、NodeInserted:Occurs when a node belonging to the document is inserted into another node.
- NodeRemoving、NodeRemoved:Occurs when a node belonging to the document has been removed from its parent.
3. XML element: XmlElement
1. Attributes:
- HasAttributes: Gets a boolean value indicating whether the current node has any attributes.
- IsEmpty: Get or set the marking format of the element.
- SchemaInfo: Get the post-schema verification information set assigned to this node as the result of schema verification.
2. Method:
- GetAttribute(String): Returns the value of the attribute with the specified name.
- GetAttributeNode(String): Returns XmlAttribute with the specified name.
- HasAttribute(String): Determines whether the current node has a characteristic with the specified name.
- GetElementsByTagName(String): Returns an XmlNodeList that contains a list of all child elements that match the specified Name.
- RemoveAllAttributes() : Removes all specified properties from the element. The default feature is not removed.
- RemoveAttribute(String): Removes attributes by name.
- RemoveAttributeAt(Int32): Removes the attribute node with the specified index from the element. (If the removed feature has a default value, it will be replaced immediately).
- RemoveAttributeNode(String, String): Removes the XmlAttribute specified by the local name and namespace URI. (If the removed feature has a default value, it will be replaced immediately)
3. Create and query XML
Namespaces to be added:
using ;
1. Create XmlDocument
XmlDocument xmldoc = new XmlDocument(); //Add to XML declaration paragraph,XmlDeclaration xmldecl; xmldecl = ("1.0", "gb2312", null); (xmldecl); //Add a root elementXmlElement xmlelem = ("", "Employees", ""); (xmlelem); //Add another elementfor (int i = 1; i < 3; i++) { XmlNode root = ("Employees");//Find XmlElement xe1 = ("Node");//Create a node ("genre", "Li Zanhong");//Set the genre attribute of this node ("ISBN", "2-3631-4");//Set the ISBN attribute of this node XmlElement xesub1 = ("title"); = "CS from Beginner to Mastery";//Set text node (xesub1);//Add to node XmlElement xesub2 = ("author"); = "Hou Jie"; (xesub2); XmlElement xesub3 = ("price"); = "58.3"; (xesub3); (xe1);//Add to node } //Save the created XML document("../../");
Result: A file named is generated, with the following contents,
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="Li Zanhong" ISBN="2-3631-4"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> <Node genre="Li Zanhong" ISBN="2-3631-4"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> </Employees>
2. Create XmlTextWriter
See:XmlReader and XMLWriter (abstract class)
string strFilename = "../../"; XmlTextWriter xmlWriter = new XmlTextWriter(strFilename, );// Create axmldocument = ; (); ("Employees"); ("Node"); ("genre", "Li Zanhong"); ("ISBN", "2-3631-4"); ("title"); ("CS from Beginner to Mastery"); (); ("author"); ("Hou Jie"); (); ("price"); ("58.3"); (); (); (); ();
result:
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="Li Zanhong" ISBN="2-3631-4"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> </Employees>
3. Create XML fragments: ()
XmlDocument xmldoc = new XmlDocument(); XmlDocumentFragment docFrag = (); = "aa"; (); XmlElement root = ; (docFrag);
4. Load the existing XML file: ()
XmlDocument xmldoc = new XmlDocument(); (("")); XmlElement root = ;//Get the root elementforeach (XmlNode node in ) { if (["gere"].Value == "a") { foreach (XmlNode node1 in ) { if ( == "author") { = "aa";//Modify the text } } } }
5. Query node: SelectNodes
string str = @" 200 Authentication information matching "; var xd = new (); (str);//xml loads xml string XmlNamespaceManager nsManager = new XmlNamespaceManager();//Create a namespace manager ("xsd", "http:///2001/XMLSchema");// When adding strings, the namespace manager will atomize these strings.("xsi", "http:///2001/XMLSchema-instance"); ("amon", "/"); var rowNoteList = ("//amon:ErrorRes", nsManager);//Find nodes(rowNoteList[0]);
return:
<ErrorRes xmlns="/"> <Err_code>200</Err_code> <Err_content>Authentication information matching</Err_content> </ErrorRes>
6. Read xml:StreamReader according to text file
StreamReader myFile = new StreamReader("../../", );//Notice string myString = ();//myString is a read string(); (myString);
4. Add a node: AppendChild
XmlDocument xmlDoc = new XmlDocument(); ("../../"); XmlNode root = ("Employees");//Find XmlElement xe1 = ("Node");//Create a node ("genre", "Zhang San");//Set the genre attribute of this node("ISBN", "1-1111-1");//Set the ISBN attribute of this node XmlElement xesub1 = ("title"); = "C#Beginner Help";//Set Text Node (xesub1);//Add to node XmlElement xesub2 = ("author"); = "Master"; (xesub2); XmlElement xesub3 = ("price"); = "158.3"; (xesub3); (xe1);//Add to node ("../../");
Result: A node was added to the original content of the xml, with the following content,
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="Li Zanhong" ISBN="2-3631-4"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> <Node genre="Li Zanhong" ISBN="2-3631-4"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> <Node genre="Zhang San" ISBN="1-1111-1"> <title>C#Beginner Help</title> <author>Expert</author> <price>158.3</price> </Node> </Employees>
5. Modify nodes
1. Modify the value of the node (properties and subnodes):
XmlDocument xmlDoc = new XmlDocument(); ("../../"); XmlNodeList nodeList = ("Employees").ChildNodes;//Get all child nodes of Employees node foreach (XmlNode xn in nodeList)//Transfer all child nodes{ XmlElement xe = (XmlElement)xn;//Convert child node type to XmlElement type if (("genre") == "Zhang San")//If the genre attribute value is "Zhang San" { ("genre", "update Zhang San");//Then modify this property to "update Zhang San" XmlNodeList nls = ;//Continue to get all children of xe child nodes foreach (XmlNode xn1 in nls)//Travel { XmlElement xe2 = (XmlElement)xn1;//Convert type if ( == "author")//If found { = "Asia Victory";//Modify } } } } ("../../");//save。
Result: All the original node information has been modified, the content of the xml is as follows.
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="Li Zanhong" ISBN="2-3631-4"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> <Node genre="Li Zanhong" ISBN="2-3631-4"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> <Node genre="update Zhang San" ISBN="1-1111-1"> <title>C#Beginner Help</title> <author>Asia Win</author> <price>158.3</price> </Node> </Employees>
2. Modify nodes (add node properties and add node sub-nodes)
XmlDocument xmlDoc = new XmlDocument(); ("../../"); XmlNodeList nodeList = ("Employees").ChildNodes;//Get all child nodes of Employees node foreach (XmlNode xn in nodeList) { XmlElement xe = (XmlElement)xn; ("test", "111111");//Add attributes XmlElement xesub = ("flag"); = "1"; (xesub);//Add child nodes} ("../../");
Result: One property of each node is added, and one child node is also added, the content is as follows.
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="Li Zanhong" ISBN="2-3631-4" test="111111"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> <flag>1</flag> </Node> <Node genre="Li Zanhong" ISBN="2-3631-4" test="111111"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> <flag>1</flag> </Node> <Node genre="update Zhang San" ISBN="1-1111-1" test="111111"> <title>C#Beginner Help</title> <author>Asia Win</author> <price>158.3</price> <flag>1</flag> </Node> </Employees>
6. Delete nodes
1. Delete a certain attribute in the node:
XmlDocument xmlDoc = new XmlDocument(); ("../../"); XmlNodeList xnl = ("Employees").ChildNodes; foreach (XmlNode xn in xnl) { XmlElement xe = (XmlElement)xn; ("genre");//Delete the genre attribute XmlNodeList nls = ;//Continue to get all children of xe child nodes foreach (XmlNode xn1 in nls)//Travel { XmlElement xe2 = (XmlElement)xn1;//Convert type if ( == "flag")//If found { (xe2);//Delete } } } ("../../");
Result: A property of a node and a child node of a node are deleted. The content is as follows.
<xml version="1.0" encoding="gb2312"?> <Employees> <Node ISBN="2-3631-4" test="111111"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> <Node ISBN="2-3631-4" test="111111"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> <Node ISBN="1-1111-1" test="111111"> <title>C#Beginner Help</title> <author>Asia Win</author> <price>158.3</price> </Node> </Employees>
2. Delete nodes:
XmlDocument xmlDoc = new XmlDocument(); ("../../"); XmlNode root = ("Employees"); XmlNodeList xnl = ("Employees").ChildNodes; for (int i = 0; i < ; i++) { XmlElement xe = (XmlElement)(i); if (("genre") == "Zhang San") { (xe); if (i < ) i = i - 1; } } ("../../");
Result: All nodes that meet the conditions were deleted, the original content:
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="Li Zanhong" ISBN="2-3631-4"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> <Node genre="Li Zanhong" ISBN="2-3631-4"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> <Node genre="Zhang San" ISBN="1-1111-1"> <title>C#Beginner Help</title> <author>Expert</author> <price>158.3</price> </Node> <Node genre="Zhang San" ISBN="1-1111-1"> <title>C#Beginner Help</title> <author>Expert</author> <price>158.3</price> </Node> </Employees>
Deleted content:
<xml version="1.0" encoding="gb2312"?> <Employees> <Node genre="Li Zanhong" ISBN="2-3631-4"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> <Node genre="Li Zanhong" ISBN="2-3631-4"> <title>CSFrom Beginner to Mastery</title> <author>Hou Jie</author> <price>58.3</price> </Node> </Employees>
3. Replace child elements
XmlElement elem=("title"); ="XX"; (elem,);
This is all about this article about C# using XmlDocument to operate XML. I hope it will be helpful to everyone's learning and I hope everyone will support me more.