ASP. NET XmlDocument

Source: Internet
Author: User
Tags baseuri

ASP. NET XmlDocument

This article mainly introduces the ASP. NET XmlDocument class details. This article describes the attributes of XmlDocument, the method of XmlDocument, the events of XmlDocument, and the usage examples of XmlDocument. For more information, see

The XmlDocument class is the DOC parser of the. NET Framework. XmlDocument regards XML as a tree structure. It loads XML documents and builds the tree structure of this document in the memory. Next, let's take a look at what functions XmlDocument provides.

I. attributes:

Attributes obtains an XmlAttributeCollection, which contains the Attributes of the node. (Inherited from XmlNode .)

BaseURI: obtains the base URI of the current node. (Rewrite XmlNode...:. BaseURI .)

ChildNodes obtains all child nodes of a node. (Inherited from XmlNode .)

DocumentElement gets the root XmlElement of the document.

DocumentType: Get the node that contains the DOCTYPE declaration.

FirstChild obtains the first child level of the node. (Inherited from XmlNode .)

HasChildNodes gets a value indicating whether the node has any subnodes. (Inherited from XmlNode .)

Implementation gets the XmlImplementation object of the current document.

InnerText gets or sets the serial value of the node and all its subnodes. (Inherited from XmlNode .)

InnerXml gets or sets the child-level flag of the current node. (Rewrite XmlNode...:. InnerXml .)

IsReadOnly gets a value indicating whether the current node is read-only. (Rewrite XmlNode...:. IsReadOnly .)

Item has been overloaded.

LastChild obtains the last child level of the node. (Inherited from XmlNode .)

LocalName: Obtain the local name of the node. (Rewrite XmlNode...:. LocalName .)

Name: obtains the Name of a node. (Rewrite XmlNode...:. Name .)

NamespaceURI: Obtain the namespace URI of the node. (Inherited from XmlNode .)

NameTable gets the XmlNameTable associated with this implementation.

NextSibling obtains the node that follows the node. (Inherited from XmlNode .)

NodeType gets the type of the current node. (Rewrite XmlNode...:. NodeType .)

OuterXml indicates the tag of this node and all its subnodes. (Inherited from XmlNode .)

OwnerDocument gets the XmlDocument to which the current node belongs. (Rewrite XmlNode...:. OwnerDocument .)

The ParentNode has been overloaded.

Get or set the namespace Prefix of the node. (Inherited from XmlNode .)

PreserveWhitespace gets or sets a value that indicates whether to retain white space in the element content.

Previussibling gets the node that follows the node. (Inherited from XmlNode .)

SchemaInfo returns the post-architecture verification information set (PSVI) of the node ). (Rewrite XmlNode...:. SchemaInfo .)

Schemas gets or sets the XmlSchemaSet object associated with this XmlDocument.

Value to obtain or set the Value of a node. (Inherited from XmlNode .)

XmlResolver sets XmlResolver for parsing external resources.

Ii. Method

AppendChild adds the specified node to the end of the node's subnode list. (Inherited from XmlNode .)

Clone to create a copy of this node. (Inherited from XmlNode .)

CloneNode creates a copy of this node. (Rewrite XmlNode...:. CloneNode (Boolean ).)

CreateAttribute is overloaded. Create an XmlAttribute with the specified name.

CreateCDataSection: Create an XmlCDataSection that contains the specified data.

CreateComment creates an XmlComment that contains the specified data.

CreateDefaultAttribute creates a default attribute with the specified prefix, local name, and namespace URI.

CreateDocumentFragment: Create XmlDocumentFragment.

CreateDocumentType returns the new XmlDocumentType object.

The CreateElement has been overloaded. Create an XmlElement.

CreateEntityReference: Create an XmlEntityReference with the specified name.

CreateNavigator is overloaded. Create a new XPathNavigator object used to navigate this document.

CreateNode is overloaded. Create an XmlNode.

CreateProcessingInstruction: Create an XmlProcessingInstruction with the specified name and data.

CreateSignificantWhitespace: Create an XmlSignificantWhitespace node.

CreateTextNode creates XmlText with the specified text.

CreateWhitespace: Create an XmlWhitespace node.

CreateXmlDeclaration creates an XmlDeclaration node with the specified value.

GetElementById: Get the XmlElement with the specified ID.

GetElementsByTagName is overloaded. Returns an XmlNodeList that contains a list of all child elements that match the specified name.

GetEnumerator provides support for "for each" style iteration on nodes in XmlNode. (Inherited from XmlNode .)

GetHashCode is used as a hash function of a specific type. (Inherited from Object .)

GetNamespaceOfPrefix finds the xmlns statement closest to the given prefix in the current node range, and returns the namespace URI in the Declaration. (Inherited from XmlNode .)

GetPrefixOfNamespace searches for the xmlns declaration closest to the specified namespace URI within the current node range, and returns the prefix defined in the Declaration. (Inherited from XmlNode .)

ImportNode imports the node from another document to the current document.

InsertAfter inserts the specified node into the specified referenced node. (Inherited from XmlNode .)

InsertBefore inserts the specified node before the specified referenced node. (Inherited from XmlNode .)

Load has been overloaded. Load the specified XML data from Stream, URL, TextReader, or XmlReader.

LoadXml loads the XML document from the specified string.

Normalize converts all XmlText nodes in the full depth of the sub-tree under the XmlNode into the "normal" format, in this form, only labels (that is, tags, comments, processing commands, CDATA sections, and object references) are separated from XmlText nodes, that is, there are no adjacent XmlText nodes. (Inherited from XmlNode .)

PrependChild adds the specified node to the beginning of the node's subnode list. (Inherited from XmlNode .)

ReadNode creates an XmlNode object based on the information in XmlReader. The reader must be located on a node or attribute.

RemoveAll removes all child nodes and/or attributes of the current node. (Inherited from XmlNode .)

RemoveChild removes the specified subnode. (Inherited from XmlNode .)

ReplaceChild replaces the child node oldChild with the newChild node. (Inherited from XmlNode .)

Save has been reloaded. Save the XML document to the specified location.

SelectNodes is overloaded.

SelectSingleNode is overloaded.

Supports tests whether DOM implements specific functions. (Inherited from XmlNode .)

Validate is overloaded. Verify whether the XmlDocument is an XML Schema Definition Language (XSD) architecture contained in the Schemas attribute.

WriteContentTo saves all the child levels of the XmlDocument node to the specified XmlWriter. (Rewrite XmlNode ..:. WriteContentTo (XmlWriter ).)

WriteTo saves the XmlDocument node to the specified XmlWriter. (Rewrite XmlNode ..:. WriteTo (XmlWriter ).)

Iii. Events

NodeChanged occurs when the Value of the node that belongs to this document has been changed.

NodeChanging occurs when the Value of the node that belongs to this document is changed.

NodeInserted occurs when the node that belongs to this document has been inserted into another node.

NodeInserting occurs when the node that belongs to this document is inserted to another node.

NodeRemoved occurs when the node that belongs to this document has been removed from its parent.

NodeRemoving occurs when nodes belonging to this document are removed from the document.

Note attributes:

Previussibling

NextSibling

First child node of FirstChild

LastChild

ChildNodes subnode set

ParentNode parent node

Sample Code:

Xml document:

The Code is as follows:

  

  

 

Zhang San

   12000

42

  

 

Code:

The Code is as follows:

Static void Main (string [] args)

{

XmlDocument doc = new XmlDocument ();

Doc. Load (@ "C: \ Users \ Administrator \ Desktop \ ConsoleApplication1 \ ConsoleApplication1 \ Test. xml ");

// Obtain a unique Article node, the first subnode under it, and the attribute set under the node.

XmlAttributeCollection xc = doc. SelectSingleNode ("Article"). FirstChild. Attributes;

String age = xc [0]. value; // It's just a custom set, or a set of things. // string age = xc ["age"]. value; supports two types of index access

Console. WriteLine (age); // output 30

String baseuri = doc. SelectSingleNode ("Article"). FirstChild. BaseURI;

Console. WriteLine (baseuri); // output file: // C: \ Users \ Administrator \ Desktop \ ConsoleApplication1 \ ConsoleApplication1 \ Test. xml

XmlNodeList listNode = doc. SelectSingleNode ("Article"). ChildNodes; // retrieve the list of all nodes under the Article Node

For (int I = 0; I <listNode. Count; I ++) // XmlNodeList does not support foreach traversal.

{

Console. write (listNode [I]. name + ":" + listNode [I]. innerText); // The output author: Zhang San length: 12000 price: 30 Name gets the qualified Name, that is, the tag Name.

}

XmlElement xe = doc. DocumentElement; // get the root node

Console. WriteLine (xe. Name); // output Article

// XmlDocumentType xdt = doc. DocumentType; // obtain the node that contains the DOCTYPE declaration. It should be a node defined by DTD.

// Console. Write (xdt. Name); // The object reference is not set to the instance of the object, because the element declared by DOCTYPE cannot be found.

Console. WriteLine (doc. HasChildNodes); // output True whether the current Document contains a subnode.

// XmlImplementation xi = doc. Implementation; // do not know how to use

// Xi. ToString ();

Console. WriteLine (doc. InnerText); // obtain the content output of the current document. Part 3: 12000

Console. WriteLine (doc. InnerXml); // output the string content of the entire Xml file

Console. WriteLine (doc. IsReadOnly); // obtain whether the current document is read-only. Output False

XmlNode node = doc. LastChild;

Console. WriteLine (node. InnerText); // output Part 3 12000 30. Because the last node is the Article node, all content of the Article node is output.

Console. WriteLine (doc. LocalName); // output # document

Console. WriteLine (doc. SelectSingleNode ("Article"). Name); // output Article

Console. WriteLine (doc. SelectSingleNode ("Article"). FirstChild. NextSibling. Name); // length the next sibling node of author is length

XmlNodeType xnt = doc. SelectSingleNode ("Article"). NodeType;

Console. WriteLine (xnt); // output Element, indicating that this node is an Element node

String str = doc. SelectSingleNode ("Article"). OuterXml; // This node and all its own vertex tags output all content of the Article Node

Omitted...

 

Console. WriteLine (str );

XmlDocument x = new XmlDocument ();

X. LoadXml (str );

Console. WriteLine (doc. SelectSingleNode ("Article"). OwnerDocument); // obtain the XmlDocument to which the node belongs

XmlNode xn = doc. SelectSingleNode ("Article"). LastChild. ParentNode; // obtain the parent node directly.

Console. WriteLine (xn. Name); // output Article

Console. WriteLine (doc. PreserveWhitespace); // whether to retain blank output False

XmlNode xn1 = doc. SelectSingleNode ("Article"). LastChild. PreviousSibling;

Console. WriteLine (xn1.Name); // The output length is indeed the previous node of the last node.

Console. ReadKey ();

}

To better display some attributes, change xml to the following:

The Code is as follows:

  

  

  

   Zhang San

   12000

   42

  

The Code is as follows:

The Code is as follows:

Static void Main (string [] args)

{

XmlDocument doc = new XmlDocument ();

Doc. Load (@ "C: \ Users \ Administrator \ Desktop \ ConsoleApplication1 \ ConsoleApplication1 \ Test. xml ");

XmlNamespaceManager xnm = new XmlNamespaceManager (doc. NameTable );

Xnm. AddNamespace ("h", "http://www.xxx.com /");

XmlNode Article = doc. SelectSingleNode ("h: Article", xnm );

String namespace1 = Article. InnerText;

Console. WriteLine (namespace1); // output Zhang San 12000 30

Console. WriteLine (Article. Prefix); // output h to get the Prefix of the current node

Console. WriteLine (Article. NamespaceURI); // The output http://www.xxx.com/123 gets the namespace of the current node

Console. WriteLine (Article. FirstChild. Name + "---" + Article. FirstChild. Value + "---" + Article. FirstChild. LocalName );

// Output h: author ------ author

// SchemaInfo returns the post-architecture verification information set (PSVI) of the node ). // Value gets or sets the Value of a node. (Inherited from XmlNode .)

// XmlResolver sets XmlResolver for parsing external resources.

Console. ReadKey ();

}

Next, let's take a look at the common attributes of Schemas.

The Code is as follows:

Static void Main (string [] args)

{

XmlDocument doc = new XmlDocument (); // create a document

Doc. Schemas. Add (null, @ "C: \ Users \ Administrator \ Desktop \ ConsoleApplication1 \ ConsoleApplication1 \ person. xsd"); // Add a schema object to the XmlDocument

Doc. Load (@ "C: \ Users \ Administrator \ Desktop \ ConsoleApplication1 \ ConsoleApplication1 \ person. xml"); // Load the xml file

Console. WriteLine (doc. Schemas. Count); // output 1 is the one added in the second row.

Console. WriteLine (doc. SchemaInfo. MemberType );

// XmlResolver sets XmlResolver for parsing external resources.

Console. ReadKey ();

}

Next, let's try the XmlDocument method.

The code for Test. xml is as follows:

The Code is as follows:

  

  

  

   1

  

Luo Guanzhong

   2005

38.5

  

  

   2

  

Wu chengen

   2004

37.5

  

  

The main program code is as follows:

The Code is as follows:

Static void Main (string [] args)

{

XmlDocument doc = new XmlDocument (); // create a document

Doc. Load (@ "C: \ Users \ Administrator \ Desktop \ ConsoleApplication1 \ ConsoleApplication1 \ Test. xml"); // Load the xml file

XmlNode node1 = doc. CreateNode (XmlNodeType. Element, "pagecount", null );

Node1.InnerText = "222 ";

Doc. SelectSingleNode ("/bookstore"). AppendChild (node1); // after execution 222 Element Added to the front

Doc. Save (@ "D: \ 123.xml ");

XmlNode node2 = doc. SelectSingleNode ("/bookstore/book [1]/title [1]"). Clone (); // Clone a node

Console. WriteLine (node2.InnerText); // outputs Three Kingdoms

XmlNode node3 = doc. selectSingleNode ("/bookstore/book [1]/title [1]"). cloneNode (true); // The parameter determines whether to clone the number of subnodes (if false, the text node is not cloned)

Console. WriteLine (node3.InnerText); // output Three Kingdoms

XmlAttribute attr = doc. CreateAttribute ("age"); // create an age attribute

Attr. Value = "23 ";

Doc. SelectSingleNode ("/bookstore/book [1]/author [1]"). Attributes. Append (attr); // after execution, the first author becomes Luo Guanzhong

Doc. Save (@ "D: \ 123.xml ");

XmlCDataSection cdata = doc. CreateCDataSection ("I & you ");

Doc. SelectSingleNode ("/bookstore/book [1]/author [1]"). AppendChild (cdata); // after the execution, author becomes Luo Guanzhong

Doc. Save (@ "D: \ 123.xml ");

XmlComment com = doc. CreateComment ("22:37:25 ");

Doc. SelectSingleNode ("/bookstore/book [1]/title [1]"). AppendChild (com); // after execution, the title becomes

Doc. Save (@ "D: \ 123.xml ");

XmlDocument doc1 = new XmlDocument ();

XmlDocumentFragment xdf = doc1.CreateDocumentFragment (); // an xml fragment. This class is easy to use.

Xdf. InnerXml =" Widget ";

Doc1.AppendChild (xdf );

Console. WriteLine (doc1.OuterXml); // output Widget

// CreateDefaultAttribute creates a default attribute with the specified prefix, local name, and namespace URI.

// CreateDocumentType returns the new XmlDocumentType object.

XmlDocument doc2 = new XmlDocument ();

XmlElement element = doc2.CreateElement ("title"); // create a title. If it is saved as an output;

XPathNavigator nav = doc2.CreateNavigator (); // a cursor-based navigation model is used to traverse XML document data.

XmlText text = doc2.CreateTextNode ("hello"); // create a text node

Doc2.SelectSingleNode ("/title"). AppendChild (text );

Console. WriteLine (doc2.OuterXml); // output & h; Hello

XmlWhitespace xws = doc2.CreateWhitespace (""); // create a blank Node

Doc2.SelectSingleNode ("/title"). AppendChild (xws );

Console. WriteLine (doc2.OuterXml); // output & h; Hello

XmlDeclaration xd = doc2.CreateXmlDeclaration ("1.0", "UTF-8", "yes"); // xml header XML declaration Section

XmlNode root = doc2.SelectSingleNode ("/title ");

Doc2.InsertBefore (xd, root );

Console. WriteLine (doc2.OuterXml); // added to the header after execution

XmlSignificantWhitespace xsw = doc2.CreateSignificantWhitespace ("");

XmlElement ele = doc2.CreateElement ("white ");

Ele. InnerText = "blank ";

Ele. AppendChild (xsw );

Doc2.SelectSingleNode ("/title"). AppendChild (ele );

Console. WriteLine (doc2.OuterXml); // you can add a lot of white space.

XmlDocument doc3 = new XmlDocument ();

String PItext = "type = 'text/xsl 'href = 'book. xsl '";

XmlProcessingInstruction newPI = doc3.CreateProcessingInstruction ("xml-stylesheet", PItext );

Doc3.AppendChild (newPI );

Console. WriteLine (doc3.OuterXml); // output

// GetElementById gets the XmlElement with the specified ID.

// GetElementsByTagName is overloaded. Returns an XmlNodeList that contains a list of all child elements that match the specified name.

// GetEnumerator provides support for "for each" style iteration on nodes in XmlNode. (Inherited from XmlNode .)

// GetNamespaceOfPrefix finds the xmlns declaration closest to the given prefix in the current node range, and returns the namespace URI in the Declaration. (Inherited from XmlNode .)

// GetPrefixOfNamespace searches for the xmlns declaration closest to the specified namespace URI within the current node range, and returns the prefix defined in the Declaration. (Inherited from XmlNode .)

// ImportNode imports the node from another document to the current document.

// InsertAfter inserts the specified node into the specified referenced node. (Inherited from XmlNode .)

// InsertBefore inserts the specified node before the specified referenced node. (Inherited from XmlNode .)

// LoadXml loads the XML document from the specified string.

// Normalize converts all XmlText nodes in the full depth of the sub-tree under the XmlNode into the "normal" format, in this form, only labels (that is, tags, comments, processing commands, CDATA sections, and object references) are separated from XmlText nodes, that is, there are no adjacent XmlText nodes. (Inherited from XmlNode .)

// PrependChild adds the specified node to the beginning of the node's subnode list. (Inherited from XmlNode .)

// ReadNode creates an XmlNode object based on the information in XmlReader. The reader must be located on a node or attribute.

// RemoveAll removes all child nodes and/or attributes of the current node. (Inherited from XmlNode .)

// RemoveChild removes the specified subnode. (Inherited from XmlNode .)

// ReplaceChild replace the child oldChild with the newChild node. (Inherited from XmlNode .)

// Supports test whether DOM implements specific functions. (Inherited from XmlNode .)

// Validate is overloaded. Verify whether the XmlDocument is an XML Schema Definition Language (XSD) architecture contained in the Schemas attribute.

// WriteContentTo save all child levels of the XmlDocument node to the specified XmlWriter. (Rewrite XmlNode ..:. WriteContentTo (XmlWriter ).)

// WriteTo Save the XmlDocument node to the specified XmlWriter. (Rewrite XmlNode ..:. WriteTo (XmlWriter ).)

Console. ReadKey ();

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.