public class XmlDocument : XmlNode
|
The XmlDataDocument class extends XmlDocument and allows structured data to be stored, retrieved, and manipulated through a relational DataSet. This class allows components to mix XML and relational views of the underlying data.
ctor #1 | Overloaded:.ctor() Default constructor. This constructor is called by derived class constructors to initialize state in this type.Initializes a new instance of the XmlDocument class. |
ctor #3 | Overloaded:.ctor(XmlNameTable nt) Initializes a new instance of the XmlDocument class with the specified XmlNameTable. |
Attributes (inherited from System.Xml.XmlNode) |
Read-only See base class member description: System.Xml.XmlNode.Attributes Gets an XmlAttributeCollection containing the attributes of this node. |
BaseURI | Read-only Overridden: Gets the base URI of the current node. |
ChildNodes (inherited from System.Xml.XmlNode) |
Read-only See base class member description: System.Xml.XmlNode.ChildNodes Gets all the children of the node. |
DocumentElement | Read-only Gets the root XmlElement for the document. |
DocumentType | Read-only Gets the node containing the DOCTYPE declaration. |
FirstChild (inherited from System.Xml.XmlNode) |
Read-only See base class member description: System.Xml.XmlNode.FirstChild Gets the first child of the node. |
HasChildNodes (inherited from System.Xml.XmlNode) |
Read-only See base class member description: System.Xml.XmlNode.HasChildNodes Gets a value indicating whether this node has any child nodes. |
Implementation | Read-only Gets the XmlImplementation object for the current document. |
InnerText (inherited from System.Xml.XmlNode) |
Read-write See base class member description: System.Xml.XmlNode.InnerText Gets or sets the concatenated values of the node and all its children. |
InnerXml | Read-write Overridden: Gets or sets the markup representing the children of the current node. |
IsReadOnly | Read-only Overridden: Gets a value indicating whether the current node is read-only. |
Item (inherited from System.Xml.XmlNode) |
Read-only Overloaded: Item[string name] {get See base class member description: System.Xml.XmlNode.ItemGets the first child element with the specified XmlNode.Name. |
Item (inherited from System.Xml.XmlNode) |
Read-only Overloaded: Item[string localname, string ns] {get See base class member description: System.Xml.XmlNode.ItemGets the first child element with the specified XmlNode.LocalName and XmlNode.NamespaceURI. |
LastChild (inherited from System.Xml.XmlNode) |
Read-only See base class member description: System.Xml.XmlNode.LastChild Gets the last child of the node. |
LocalName | Read-only Overridden: Gets the local name of the node. |
Name | Read-only Overridden: Gets the qualified name of the node. |
NamespaceURI (inherited from System.Xml.XmlNode) |
Read-only See base class member description: System.Xml.XmlNode.NamespaceURI Gets the namespace URI of this node. |
NameTable | Read-only Gets the XmlNameTable associated with this implementation. |
NextSibling (inherited from System.Xml.XmlNode) |
Read-only See base class member description: System.Xml.XmlNode.NextSibling Gets the node immediately following this node. |
NodeType | Read-only Overridden: Gets the type of the current node. |
OuterXml (inherited from System.Xml.XmlNode) |
Read-only See base class member description: System.Xml.XmlNode.OuterXml Gets the markup representing this node and all its children. |
OwnerDocument | Read-only Overridden: Gets the XmlDocument to which the current node belongs. |
ParentNode (inherited from System.Xml.XmlNode) |
Read-only See base class member description: System.Xml.XmlNode.ParentNode Gets the parent of this node (for nodes that can have parents). |
Prefix (inherited from System.Xml.XmlNode) |
Read-write See base class member description: System.Xml.XmlNode.Prefix Gets or sets the namespace prefix of this node. |
PreserveWhitespace | Read-write Gets or sets a value indicating whether to preserve white space. |
PreviousSibling (inherited from System.Xml.XmlNode) |
Read-only See base class member description: System.Xml.XmlNode.PreviousSibling Gets the node immediately preceding this node. |
Value (inherited from System.Xml.XmlNode) |
Read-write See base class member description: System.Xml.XmlNode.Value Gets or sets the value of the node. |
XmlResolver | Write-only Sets the XmlResolver to use for resolving external resources. |
AppendChild (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.AppendChild Adds the specified node to the end of the list of children of this node. |
Clone (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.Clone Creates a duplicate of this node. |
CloneNode | Overridden: Creates a duplicate of this node. |
CreateAttribute | Overloaded:CreateAttribute(string name) Creates an XmlAttribute with the specified XmlDocument.Name. |
CreateAttribute | Overloaded:CreateAttribute(string qualifiedName, string namespaceURI) Creates an XmlAttribute with the specified qualified name and XmlNode.NamespaceURI. |
CreateAttribute | Overloaded:CreateAttribute(string prefix, string localName, string namespaceURI) Creates an XmlAttribute with the specified XmlNode.Prefix, XmlDocument.LocalName, and XmlNode.NamespaceURI. |
CreateCDataSection | Creates an XmlCDataSection containing the specified data. |
CreateComment | Creates an XmlComment containing the specified data. |
CreateDocumentFragment | Creates an XmlDocumentFragment. |
CreateDocumentType | Returns a new XmlDocumentType object. |
CreateElement | Overloaded:CreateElement(string name) Creates an element with the specified name. |
CreateElement | Overloaded:CreateElement(string qualifiedName, string namespaceURI) Creates an XmlElement with the qualified name and XmlNode.NamespaceURI. |
CreateElement | Overloaded:CreateElement(string prefix, string localName, string namespaceURI) Creates an element with the specified XmlNode.Prefix, XmlDocument.LocalName, and XmlNode.NamespaceURI. |
CreateEntityReference | Creates an XmlEntityReference with the specified name. |
CreateNavigator (inherited from System.Xml.XmlNode) |
Overloaded:CreateNavigator() See base class member description: System.Xml.XmlNode.CreateNavigatorCreates an XPathNavigator for navigating this object. |
CreateNode | Overloaded:CreateNode(string nodeTypeString, string name, string namespaceURI) Creates an XmlNode with the specified node type, XmlDocument.Name, and XmlNode.NamespaceURI. |
CreateNode | Overloaded:CreateNode(XmlNodeType type, string name, string namespaceURI) Creates an XmlNode with the specified XmlNodeType, XmlDocument.Name, and XmlNode.NamespaceURI. |
CreateNode | Overloaded:CreateNode(XmlNodeType type, string prefix, string name, string namespaceURI) Creates a XmlNode with the specified XmlNodeType, XmlNode.Prefix, XmlDocument.Name, and XmlNode.NamespaceURI. |
CreateProcessingInstruction | Creates an XmlProcessingInstruction with the specified name and data. |
CreateSignificantWhitespace | Creates an XmlSignificantWhitespace node. |
CreateTextNode | Creates an XmlText with the specified text. |
CreateWhitespace | Creates an XmlWhitespace node. |
CreateXmlDeclaration | Creates an XmlDeclaration node with the specified values. |
Equals (inherited from System.Object) |
See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
GetElementById | Gets the XmlElement with the specified ID. |
GetElementsByTagName | Overloaded:GetElementsByTagName(string name) Returns an XmlNodeList containing a list of all descendant elements that match the specified XmlDocument.Name. |
GetElementsByTagName | Overloaded:GetElementsByTagName(string localName, string namespaceURI) Returns an XmlNodeList containing a list of all descendant elements that match the specified XmlDocument.LocalName and XmlNode.NamespaceURI. |
GetEnumerator (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.GetEnumerator Provides support for the for each style iteration over the nodes in the XmlNode. |
GetHashCode (inherited from System.Object) |
See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
GetNamespaceOfPrefix (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.GetNamespaceOfPrefix Looks up the closest xmlns declaration for the given prefix that is in scope for the current node and returns the namespace URI in the declaration. |
GetPrefixOfNamespace (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.GetPrefixOfNamespace Looks up the closest xmlns declaration for the given namespace URI that is in scope for the current node and returns the prefix defined in that declaration. |
GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
ImportNode | Imports a node from another document to the current document. |
InsertAfter (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.InsertAfter Inserts the specified node immediately after the specified reference node. |
InsertBefore (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.InsertBefore Inserts the specified node immediately before the specified reference node. |
Load | Overloaded:Load(Stream inStream) Loads the XML document from the specified stream. |
Load | Overloaded:Load(string filename) Loads the XML document from the specified URL. |
Load | Overloaded:Load(TextReader txtReader) Loads the XML document from the specified TextReader. |
Load | Overloaded:Load(XmlReader reader) Loads the XML document from the specified XmlReader. |
LoadXml | Loads the XML document from the specified string. |
Normalize (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.Normalize Puts all XmlText nodes in the full depth of the sub-tree underneath this XmlNode into a "normal" form where only markup (that is, tags, comments, processing instructions, CDATA sections, and entity references) separates XmlText nodes, that is, there are no adjacent XmlText nodes. |
PrependChild (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.PrependChild Adds the specified node to the beginning of the list of children of this node. |
ReadNode | Creates an XmlNode object based on the information in the XmlReader. The reader must be positioned on a node or attribute. |
RemoveAll (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.RemoveAll Removes all the children and/or attributes of the current node. |
RemoveChild (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.RemoveChild Removes specified child node. |
ReplaceChild (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.ReplaceChild Replaces the child node oldChild with newChild node. |
Save | Overloaded:Save(Stream outStream) Saves the XML document to the specified stream. |
Save | Overloaded:Save(string filename) Saves the XML document to the specified file. |
Save | Overloaded:Save(TextWriter writer) Saves the XML document to the specified TextWriter. |
Save | Overloaded:Save(XmlWriter w) Saves the XML document to the specified XmlWriter. |
SelectNodes (inherited from System.Xml.XmlNode) |
Overloaded:SelectNodes(string xpath) See base class member description: System.Xml.XmlNode.SelectNodesSelects a list of nodes matching the XPath expression. |
SelectNodes (inherited from System.Xml.XmlNode) |
Overloaded:SelectNodes(string xpath, XmlNamespaceManager nsmgr) See base class member description: System.Xml.XmlNode.SelectNodesSelects a list of nodes matching the XPath expression. Any prefixes found in the XPath expression are resolved using the supplied XmlNamespaceManager. |
SelectSingleNode (inherited from System.Xml.XmlNode) |
Overloaded:SelectSingleNode(string xpath) See base class member description: System.Xml.XmlNode.SelectSingleNodeSelects the first XmlNode that matches the XPath expression. |
SelectSingleNode (inherited from System.Xml.XmlNode) |
Overloaded:SelectSingleNode(string xpath, XmlNamespaceManager nsmgr) See base class member description: System.Xml.XmlNode.SelectSingleNodeSelects the first XmlNode that matches the XPath expression. Any prefixes found in the XPath expression are resolved using the supplied XmlNamespaceManager. |
Supports (inherited from System.Xml.XmlNode) |
See base class member description: System.Xml.XmlNode.Supports Test if the DOM implementation implements a specific feature. |
ToString (inherited from System.Object) |
See base class member description: System.Object.ToString Derived from System.Object, the primary base class for all objects. |
WriteContentTo | Overridden: Saves all the children of the XmlDocument node to the specified XmlWriter. |
WriteTo | Overridden: Saves the XmlDocument node to the specified XmlWriter. |
NodeChanged | Occurs when the XmlNode.Value of a node belonging to this document has been changed. |
NodeChanging | Occurs when the XmlNode.Value of a node belonging to this document is about to be changed. |
NodeInserted | Occurs when a node belonging to this document has been inserted into another node. |
NodeInserting | Occurs when a node belonging to this document is about to be inserted into another node. |
NodeRemoved | Occurs when a node belonging to this document has been removed from its parent. |
NodeRemoving | Occurs when a node belonging to this document is about to be removed from the document. |
ctor #2 | Overloaded:.ctor(XmlImplementation imp) Initializes a new instance of the XmlDocument class with the specified XmlImplementation. |
CreateDefaultAttribute | Creates a default attribute with the specified prefix, local name and namespace URI. |
CreateNavigator | Overloaded:CreateNavigator(XmlNode node) Creates an XPathNavigator object for navigating this document. |
Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
public XmlDocument(); |
protected internal XmlDocument( |
imp
public XmlDocument( |
nt
public virtual XmlAttributeCollection Attributes {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book xmlns:bk='urn:samples' bk:ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); XmlNode root = doc.FirstChild; //Create a new attribute. string ns = root.GetNamespaceOfPrefix("bk"); XmlNode attr = doc.CreateNode(XmlNodeType.Attribute, "genre", ns); attr.Value = "novel"; //Add the attribute to the document. root.Attributes.SetNamedItem(attr); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
public override string BaseURI {get;}
|
For Document nodes, BaseURI returns the location of the XML document. For example, if the XmlDocument was loaded using the following call doc.Load("http://server/mydata.xml"), the BaseURI for the document node is http://server/mydata.xml .
This property is a Microsoft extension to the Document Object Model (DOM). For additional information on BaseURI and how it behaves with other node types, see the XmlNode.BaseURI property in the XmlNode class.
public virtual XmlNodeList ChildNodes {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "<price>19.95</price>" + "</book>"); XmlNode root = doc.FirstChild; //Display the contents of the child nodes. if (root.HasChildNodes) { for (int i=0; i<root.ChildNodes.Count; i++) { Console.WriteLine(root.ChildNodes[i].InnerText); } } } }
public XmlElement DocumentElement {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<?xml version='1.0' ?>" + "<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Display the document element. Console.WriteLine(doc.DocumentElement.OuterXml); } }
public virtual XmlDocumentType DocumentType {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { // Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<!DOCTYPE book [<!ENTITY h 'hardcover'>]>" + "<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "<style>&h;</style>" + "</book>"); // Display the DocumentType. Console.WriteLine(doc.DocumentType.OuterXml); } }
public virtual XmlNode FirstChild {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "<price>19.95</price>" + "</book>"); XmlNode root = doc.FirstChild; Console.WriteLine("Display the title element..."); Console.WriteLine(root.FirstChild.OuterXml); } }
public virtual bool HasChildNodes {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "<price>19.95</price>" + "</book>"); XmlNode root = doc.FirstChild; //Display the contents of the child nodes. if (root.HasChildNodes) { for (int i=0; i<root.ChildNodes.Count; i++) { Console.WriteLine(root.ChildNodes[i].InnerText); } } } }
public XmlImplementation Implementation {get;}
|
Although the XmlDocument objects share the same implementation, to move nodes from one document to another you must use the XmlDocument.ImportNode method.
XmlDocument doc1 = new XmlDocument(); doc1.Load("books.xml"); XmlDocument doc2 = doc1.Implementation.CreateDocument();
public virtual string InnerText {get; set;}
|
For leaf nodes, InnerText returns the same content as the XmlNode.Value property.
This property is a Microsoft extension to the Document Object Model (DOM).
using System; using System.Xml; public class Test { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<root>"+ "<elem>some text<child/>more text</elem>" + "</root>"); XmlNode elem = doc.DocumentElement.FirstChild; //Note that InnerText does not include the markup. Console.WriteLine("Display the InnerText of the element..."); Console.WriteLine( elem.InnerText ); //InnerXml includes the element's markup. Console.WriteLine("Display the InnerXml of the element..."); Console.WriteLine(elem.InnerXml); //Set InnerText to a string that includes markup. //The markup is entitized. elem.InnerText = "Text containing <markup/> will have char(<) and char(>) entitized."; Console.WriteLine( elem.OuterXml ); //Set InnerXml to a string that includes markup. //The markup is not entitized. elem.InnerXml = "Text containing <markup/>."; Console.WriteLine( elem.OuterXml ); } }
public override string InnerXml {get; set;}
|
InnerXml removes redundant namespace declarations. As a result, numerous cut and paste operations do not increase the size of your document with redundant namespace declarations. Consider the following XSL document:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="stock"> ... </xsl:template> </xsl:stylesheet>
The InnerXml property on the stylesheet node returns the following string:
<xsl:template match="stock" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> ... </xsl:template>
Notice the additional xmlns:xsl namespace declaration which is used to preserve the node identity. If you re-insert this inner XML string, you will get back your original document. In other words, InnerXml recognizes that the xmlns:xsl namespace declaration is redundant, given that the parent xsl:stylesheet element already has the xmlns:xsl namespace delcaration, and therefore removes it.
If you move InnerXml from a document with no default namespace to a document with a default namespace, the behavior is a little different. Consider the following XML string:
<test> <item>123</item> </test>
InnerXml returns a plain XML string with no namespace declarations:
<item>123</item>
If you then insert this string into a document that does have a default namespace, such as the following:
<test2 xmlns="urn:1"> </test>
InnerXml parses the string in context, and the new nodes pick up the urn:1 namespace. The result looks like this:
<test2 xmlns="urn:1"> <item>123</item> </test>
Now when you ask for the InnerXml you get back the following:
<item xmlns="urn:1">123</item>
If you explicitly want the inserted item to preserve the fact that it came from a document that had no namespace then you need to manually add an xmlns= "" declaration and insert the resulting string:
<item xmlns="">123</item>
The net effect of all this is as follows:
If InnerXml is set with text containing entity references that are not currently defined in the document, the resulting tree will contain empty EntityReference nodes.
This property is a Microsoft extension to the Document Object Model (DOM).
public override bool IsReadOnly {get;}
|
This property is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<!DOCTYPE book [<!ENTITY h 'hardcover'>]>" + "<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "<style>&h;</style>" + "</book>"); //Check if the node is read-only. if (doc.DocumentElement.LastChild.FirstChild.IsReadOnly) Console.WriteLine("Entity reference nodes are always read-only"); } }
public virtual XmlElement this[string name] {get;}
|
name
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "<price>19.95</price>" + "</book>"); XmlNode root = doc.FirstChild; Console.WriteLine("Display the title element..."); Console.WriteLine(root["title"].OuterXml); } }
public virtual XmlElement this[string localname, string ns] {get;}
|
localname
ns
public virtual XmlNode LastChild {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "<price>19.95</price>" + "</book>"); XmlNode root = doc.FirstChild; Console.WriteLine("Display the price element..."); Console.WriteLine(root.LastChild.OuterXml); } }
public override string LocalName {get;}
|
public override string Name {get;}
|
public virtual string NamespaceURI {get;}
|
An attribute does not inherit its namespace from the element it is attached to. If an attribute is not explicitly given a namespace, it simply has no namespace.
public XmlNameTable NameTable {get;}
|
For more information on atomized strings, see XmlNameTable.
This method is a Microsoft extension to the Document Object Model (DOM).
public virtual XmlNode NextSibling {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { Sample test = new Sample(); } public Sample() { try { XmlDocument doc = new XmlDocument(); doc.LoadXml("<?xml version=\"1.0\"?>" + "<!-- Sample XML document -->" + "<bookstore>" + " <book genre=\"novel\" publicationdate=\"1997\" " + " ISBN=\"1-861001-57-5\">" + " <title>Pride And Prejudice</title>" + " <author>" + " <first-name>Jane</first-name>" + " <last-name>Austen</last-name>" + " </author>" + " <price>24.95</price>" + " </book>" + " <book genre=\"novel\" publicationdate=\"1992\" " + " ISBN=\"1-861002-30-1\">" + " <title>The Handmaid's Tale</title>" + " <author>" + " <first-name>Margaret</first-name>" + " <last-name>Atwood</last-name>" + " </author>" + " <price>29.95</price>" + " </book>" + "</bookstore>"); XmlNode currNode = doc.DocumentElement; //print out books if (currNode.HasChildNodes){ XmlNode book = currNode.FirstChild; Console.WriteLine(book.OuterXml + "\n"); book = currNode.FirstChild.NextSibling; Console.WriteLine(book.OuterXml); } } catch (Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } } }
public override XmlNodeType NodeType {get;}
|
public virtual string OuterXml {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); XmlNode root = doc.DocumentElement; //OuterXml includes the markup of current node. Console.WriteLine("Display the OuterXml property..."); Console.WriteLine(root.OuterXml); //InnerXml does not include the markup of the current node. //As a result, the attributes are not displayed. Console.WriteLine(); Console.WriteLine("Display the InnerXml property..."); Console.WriteLine(root.InnerXml); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
public override XmlDocument OwnerDocument {get;}
|
public virtual XmlNode ParentNode {get;}
|
public virtual string Prefix {get; set;}
|
Exception Type | Condition |
---|---|
ArgumentException | This node is read-only |
XmlException | The specified prefix contains an illegal character The specified prefix is malformed. The specified prefix is "xml" and the namespaceURI of this node is different from "http://www.w3.org/XML/1998/namespace". This node is an attribute and the specified prefix is "xmlns" and the namespaceURI of this node is different from "http://www.w3.org/2000/xmlns/." This node is an attribute and the qualifiedName of this node is "xmlns". |
public bool PreserveWhitespace {get; set;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Load XML data which includes white space, but ignore //any white space in the file. XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = false; doc.Load("book.xml"); //Save the document as is (no white space). Console.WriteLine("Display the modified XML..."); doc.PreserveWhitespace = true; doc.Save(Console.Out); } }
The example uses the file book.xml as input.
<!--sample XML fragment--> <book genre='novel' ISBN='1-861003-78' misc='sale-item'> <title>The Handmaid's Tale</title> <price>14.95</price> </book>
public virtual XmlNode PreviousSibling {get;}
|
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { Sample test = new Sample(); } public Sample() { try { XmlDocument doc = new XmlDocument(); doc.LoadXml("<?xml version=\"1.0\"?>" + "<!-- Sample XML document -->" + "<bookstore>" + " <book genre=\"novel\" publicationdate=\"1997\" " + " ISBN=\"1-861001-57-5\">" + " <title>Pride And Prejudice</title>" + " <author>" + " <first-name>Jane</first-name>" + " <last-name>Austen</last-name>" + " </author>" + " <price>24.95</price>" + " </book>" + " <book genre=\"novel\" publicationdate=\"1992\" " + " ISBN=\"1-861002-30-1\">" + " <title>The Handmaid's Tale</title>" + " <author>" + " <first-name>Margaret</first-name>" + " <last-name>Atwood</last-name>" + " </author>" + " <price>29.95</price>" + " </book>" + "</bookstore>"); XmlNode currNode = doc.DocumentElement; //print out books in reverse order if (currNode.HasChildNodes){ XmlNode book = currNode.LastChild; Console.WriteLine(book.OuterXml + "\n"); book = currNode.LastChild.PreviousSibling; Console.WriteLine(book.OuterXml); } } catch (Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } } }
public virtual string Value {get; set;}
|
Exception Type | Condition |
---|---|
ArgumentException | The node is read-only. |
InvalidOperationException | The node is not supposed to have a value (for example, an Element node). |
XmlResolver XmlResolver {set;}
|
Exception Type | Condition |
---|---|
XmlException | This property is set to null and an external DTD or entity is encountered. |
If an XmlResolver is not specified, a default XmlUrlResolver with default credentials is used.
This property is a Microsoft extension to the Document Object Model (DOM).
newChild
Exception Type | Condition |
---|---|
InvalidOperationException | This node is of a type that does not allow children of the type of the newChild node. Or the node to be added is one of this node's ancestors. |
ArgumentException | The newChild was created from a different document than the one that created this node. This node is read-only. |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); XmlNode root = doc.DocumentElement; //Create a new node. XmlElement elem = doc.CreateElement("price"); elem.InnerText="19.95"; //Add the node to the document. root.AppendChild(elem); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
public virtual XmlNode Clone(); |
Clone is equivalent to calling
CloneNode(true)
.
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "<price>19.95</price>" + "</book>"); XmlNode root = doc.FirstChild; //Clone the root node. The cloned node includes //child nodes. This is similar to calling CloneNode(true). XmlNode clone = root.Clone(); Console.WriteLine(clone.OuterXml); } }
deep
If deep is true, the cloned node includes all the child nodes, otherwise only the XmlDocument node is cloned. See the XmlNode.CloneNode property in the XmlNode class to see how it behaves on other node types.
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Create a deep clone. The cloned node //includes the child node. XmlDocument deep = (XmlDocument) doc.CloneNode(true); Console.WriteLine(deep.ChildNodes.Count); //Create a shallow clone. The cloned node does not //include the child node. XmlDocument shallow = (XmlDocument) doc.CloneNode(false); Console.WriteLine(shallow.Name + shallow.OuterXml); Console.WriteLine(shallow.ChildNodes.Count); } }
public XmlAttribute CreateAttribute( |
name
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Create an attribute. XmlAttribute attr = doc.CreateAttribute("publisher"); attr.Value = "WorldWide Publishing"; //Add the new node to the document. doc.DocumentElement.SetAttributeNode(attr); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
public XmlAttribute CreateAttribute( |
qualifiedName
namespaceURI
public virtual XmlAttribute CreateAttribute( |
prefix
localName
namespaceURI
This method is a Microsoft extension to the Document Object Model (DOM).
public virtual XmlCDataSection CreateCDataSection( |
data
According to the W3C Extensible Markup Language (XML) 1.0 recommendation (www.w3.org/TR/1998/REC-xml-19980210), CDataSection nodes are allowed within Element nodes and in EntityReference nodes when the EntityReference node is not a child of an Attribute node.
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Create a CData section. XmlCDataSection CData; CData = doc.CreateCDataSection("All Jane Austen novels 25% off starting 3/23!"); //Add the new node to the document. XmlElement root = doc.DocumentElement; root.AppendChild(CData); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
public virtual XmlComment CreateComment( |
data
According to the W3C Extensible Markup Language (XML) 1.0 recommendation (www.w3.org/TR/1998/REC-xml-19980210), Comment nodes are only allowed within Document, Element and EntityReference nodes, when the EntityReference node is not a child of an Attribute node.
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Create a comment. XmlComment newComment; newComment = doc.CreateComment("Sample XML document"); //Add the new node to the document. XmlElement root = doc.DocumentElement; doc.InsertBefore(newComment, root); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
protected internal virtual XmlAttribute CreateDefaultAttribute( |
prefix
localName
namespaceURI
public virtual XmlDocumentFragment CreateDocumentFragment(); |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<items/>"); //Create a document fragment. XmlDocumentFragment docFrag = doc.CreateDocumentFragment(); //Set the contents of the document fragment. docFrag.InnerXml ="<item>widget</item>"; //Add the children of the document fragment to the //original document. doc.DocumentElement.AppendChild(docFrag); Console.WriteLine("Display the modified XML..."); Console.WriteLine(doc.OuterXml); } }
public virtual XmlDocumentType CreateDocumentType( |
name
publicId
systemId
internalSubset
Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. To add the new object, you must explicitly call one of the node insert methods.
According to the W3C Extensible Markup Language (XML) 1.0 recommendation (www.w3.org/TR/1998/REC-xml-19980210), DocumentType nodes are only allowed within Document nodes. Each XmlDocument can have only one DocumentType node. The DocumentType node must also be inserted before the root element of the XmlDocument (i.e if the document already has a root element, you cannot add a DocumentType node).
If the passed parameters do not combine to build a valid XmlDocumentType, an exception is thrown.
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); //Create a document type node and //add it to the document. XmlDocumentType doctype; doctype = doc.CreateDocumentType("book", null, null, "<!ELEMENT book ANY>"); doc.AppendChild(doctype); //Create the root element and //add it to the document. doc.AppendChild(doc.CreateElement("book")); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
public XmlElement CreateElement( |
name
Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. To add the new object, you must explicitly call one of the node insert methods.
According to the W3C Extensible Markup Language (XML) 1.0 recommendation (www.w3.org/TR/1998/REC-xml-19980210), Element nodes are allowed within Document and Element nodes, and in EntityReference nodes when the EntityReference node is not a child of an Attribute node.
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Create a new node and add it to the document. //The text node is the content of the price element. XmlElement elem = doc.CreateElement("price"); XmlText text = doc.CreateTextNode("19.95"); doc.DocumentElement.AppendChild(elem); doc.DocumentElement.LastChild.AppendChild(text); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
public XmlElement CreateElement( |
qualifiedName
namespaceURI
XmlElement elem; elem=doc.CreateElement("item:bar", "urn:abc");
results in an element that is equivalent to the following XML text.
<item:bar
xmlns:item="urn:abc"/>
Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. To add the new object, you must explicitly call one of the node insert methods.
According to the W3C Extensible Markup Language (XML) 1.0 recommendation (www.w3.org/TR/1998/REC-xml-19980210), Element nodes are allowed within Document and Element nodes, and in EntityReference nodes when the EntityReference node is not a child of an Attribute node.
public virtual XmlElement CreateElement( |
prefix
localName
namespaceURI
XmlElement elem; elem=doc.CreateElement("item", "bar", "urn:abc");
creates an element equivalent to the following XML text:
<item:bar xmlns:item="urn:abc"/>
Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. To add the new object, you must explicitly call one of the node insert methods.
According to the W3C Extensible Markup Language (XML) 1.0 recommendation (www.w3.org/TR/1998/REC-xml-19980210), Element nodes are allowed within Document and Element nodes, and in EntityReference nodes when the EntityReference is outside an Attribute node.
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { Sample test = new Sample(); } public Sample() { try { XmlDocument doc = new XmlDocument(); doc.LoadXml("<?xml version=\"1.0\"?>" + "<!-- Sample XML document -->" + "<bookstore xmlns:bk=\"urn:samples\">" + " <book genre=\"novel\" publicationdate=\"1997\" " + " bk:ISBN=\"1-861001-57-5\">" + " <title>Pride And Prejudice</title>" + " <author>" + " <first-name>Jane</first-name>" + " <last-name>Austen</last-name>" + " </author>" + " <price>24.95</price>" + " </book>" + " <book genre=\"novel\" publicationdate=\"1992\" " + " bk:ISBN=\"1-861002-30-1\">" + " <title>The Handmaid's Tale</title>" + " <author>" + " <first-name>Margaret</first-name>" + " <last-name>Atwood</last-name>" + " </author>" + " <price>29.95</price>" + " </book>" + "</bookstore>"); XmlNode currNode = doc.DocumentElement; //create and add a new element string prefix=currNode.GetPrefixOfNamespace("urn:samples"); XmlElement newElem=doc.CreateElement(prefix, "style", "urn:samples"); newElem.InnerText="hardcover"; currNode.FirstChild.AppendChild(newElem); Console.WriteLine("Display the modified XML..."); XmlTextWriter writer = new XmlTextWriter(Console.Out); writer.Formatting = Formatting.Indented; doc.WriteTo( writer ); writer.Flush(); writer.Close(); } catch (Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } } }
public virtual XmlEntityReference CreateEntityReference( |
name
Exception Type | Condition |
---|---|
ArgumentException | The name is invalid (for example, names starting with'#' are invalid.) |
The namespaces used in the replacement text for the entity reference are bound at the time the parent of the entity reference node is first set (for example, when the entity reference node is inserted into the document). For example, given the following entity:
<!ENTITY a "<b>test</b>">
If you call CreateEntityReference("a") you get back a single node of type EntityReference with no children. If you append this node as a child of the following node,
<item xmlns="urn:1"/>
then, at the time of calling XmlNode.AppendChild, the parent of the newly created entity reference node is set and the children are expanded in this namespace context. The child element node b will have NamespaceURI equal to urn:1. The child nodes of the entity reference remain the same even if you move the entity reference to a place in the document that has a different default namespace context. This does not happen for existing entity reference nodes when you remove and insert them or for entity references that you clone with XmlDocument.CloneNode. It only happens for newly created entity references.
If the corresponding entity is not defined in the DocumentType when the entity reference node is added, because the entity reference is not defined, its only child node will be an empty text node.
The built-in entities amp, lt, gt, apos, and quot are also allowed, and they will have a child text node with the appropriate expanded character value.
Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. To add the new object, you must explicitly call one of the node insert methods.
According to the W3C Extensible Markup Language (XML) 1.0 recommendation (www.w3.org/TR/1998/REC-xml-19980210), EntityReference nodes are only allowed within Element, Attribute and EntityReference nodes.
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<!DOCTYPE book [<!ENTITY h 'hardcover'>]>" + "<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "<misc/>" + "</book>"); //Create an entity reference node. The child count should be 0 //since the node has not been expanded. XmlEntityReference entityref = doc.CreateEntityReference("h"); Console.WriteLine(entityref.ChildNodes.Count ); //After the the node has been added to the document, its parent node //is set and the entity reference node is expanded. It now has a child //node containing the entity replacement text. doc.DocumentElement.LastChild.AppendChild(entityref); Console.WriteLine(entityref.FirstChild.InnerText); //Create and insert an undefined entity reference node. When the entity //reference node is expanded, because the entity reference is undefined //the child is an empty text node. XmlEntityReference entityref2 = doc.CreateEntityReference("p"); doc.DocumentElement.LastChild.AppendChild(entityref2); Console.WriteLine(entityref2.FirstChild.InnerText); } }
public XPathNavigator CreateNavigator(); |
This method is a Microsoft extension to the Document Object Model (DOM).
XmlDocument doc = new XmlDocument(); doc.Load("books.xml"); // Modify the XML file. XmlElement root = doc.DocumentElement; root.FirstChild.LastChild.InnerText = "12.95"; // Create an XPathNavigator to use for the transform. XPathNavigator nav = root.CreateNavigator(); // Transform the file. XslTransform xslt = new XslTransform(); xslt.Load("output.xsl"); XmlTextWriter writer = new XmlTextWriter("books.html", null); xslt.Transform(nav, null, writer);
protected internal virtual XPathNavigator CreateNavigator( |
node
public virtual XmlNode CreateNode( |
nodeTypeString
name
namespaceURI
Exception Type | Condition |
---|---|
ArgumentException | The name was not provided and the XmlNodeType requires a name; or nodeTypeString is not one of the strings listed below. |
nodeTypeString | XmlNodeType |
---|---|
attribute | Attribute |
cdatasection | CDATA |
comment | Comment |
document | Document |
documentfragment | DocumentFragment |
documenttype | DocumentType |
element | Element |
entityreference | EntityReference |
processinginstruction | ProcessingInstruction |
significantwhitespace | SignificantWhitespace |
text | Text |
whitespace | Whitespace |
Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. To add the new object, you must explicitly call one of the node insert methods.
The following table shows you what NodeType[row] is allowed inside another NodeType[column] according to the W3C Extensible Markup Language (XML) 1.0 recommendation (www.w3.org/TR/1998/REC-xml-19980210 ).
Document | DocumentType | XmlDeclaration | Element | Attribute | Text | CDATA | Markup | EntityReference | |
---|---|---|---|---|---|---|---|---|---|
Document | no | no | no | no | no | no | no | no | no |
DocumentType | yes | no | no | no | no | no | no | no | no |
XmlDeclaration | yes* | no | no | no | no | no | no | no | no |
Element | yes | no | no | yes | no | no | no | no | yes*** |
Attribute | no | no | no | yes**** | no | no | no | no | no |
Text | no | no | no | yes | yes | no | no | no | yes |
CDATA | no | no | no | yes | no | no | no | no | yes*** |
Markup** | yes | no | no | yes | no | no | no | no | no |
EntityReference | no | no | no | yes | yes | no | no | no | yes |
* The XmlDeclaration node must be the first child of the Document node.
** Markup includes ProcessingInstruction and Comment nodes.
*** Element and CDATA nodes are only allowed in EntityReference nodes when the EntityReference node is not a child of an Attribute node.
**** Attributes are not children of an Element node. Attributes are contained inside an attribute collection that belongs to an Element node.
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { Sample test = new Sample(); } public Sample() { try { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre=\"novel\" publicationdate=\"1997\" " + " ISBN=\"1-861001-57-5\">" + " <title>Pride And Prejudice</title>" + " <author>" + " <first-name>Jane</first-name>" + " <last-name>Austen</last-name>" + " </author>" + " <price>24.95</price>" + "</book>"); XmlNode newElem=doc.CreateNode("element", "pages", ""); newElem.InnerText = "290"; //add the new node to the document Console.WriteLine("Add the new element to the existing document..."); XmlElement root = doc.DocumentElement; root.AppendChild(newElem); Console.WriteLine("Display the modified xml document..."); Console.WriteLine(doc.OuterXml); } catch (Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } } }
public virtual XmlNode CreateNode( |
type
name
namespaceURI
Exception Type | Condition |
---|---|
ArgumentException | The name was not provided and the XmlNodeType requires a name. |
The following table shows you what NodeType[row] is allowed inside another NodeType[column] according to the W3C Extensible Markup Language (XML) 1.0 recommendation (www.w3.org/TR/1998/REC-xml-19980210 ).
Document | DocumentType | XmlDeclaration | Element | Attribute | Text | CDATA | Markup | EntityReference | |
---|---|---|---|---|---|---|---|---|---|
Document | no | no | no | no | no | no | no | no | no |
DocumentType | yes | no | no | no | no | no | no | no | no |
XmlDeclaration | yes* | no | no | no | no | no | no | no | no |
Element | yes | no | no | yes | no | no | no | no | yes*** |
Attribute | no | no | no | yes**** | no | no | no | no | no |
Text | no | no | no | yes | yes | no | no | no | yes |
CDATA | no | no | no | yes | no | no | no | no | yes*** |
Markup** | yes | no | no | yes | no | no | no | no | no |
EntityReference | no | no | no | yes | yes | no | no | no | yes |
* The XmlDeclaration node must be the first child of the Document node.
** Markup includes ProcessingInstruction and Comment nodes.
*** Element and CDATA nodes are only allowed in EntityReference nodes when the EntityReference node is not a child of an Attribute node.
**** Attributes are not children of an Element node. Attributes are contained inside an attribute collection that belongs to an Element node.
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Create a new node and add it to the document. XmlNode elem = doc.CreateNode(XmlNodeType.Element, "price", null); elem.InnerText = "19.95"; doc.DocumentElement.AppendChild(elem); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
public virtual XmlNode CreateNode( |
type
prefix
name
namespaceURI
Exception Type | Condition |
---|---|
ArgumentException | The name was not provided and the XmlNodeType requires a name. |
The following table shows you what NodeType[row] is allowed inside another NodeType[column] according to the W3C Extensible Markup Language (XML) 1.0 recommendation (www.w3.org/TR/1998/REC-xml-19980210 ).
Document | DocumentType | XmlDeclaration | Element | Attribute | Text | CDATA | Markup | EntityReference | |
---|---|---|---|---|---|---|---|---|---|
Document | no | no | no | no | no | no | no | no | no |
DocumentType | yes | no | no | no | no | no | no | no | no |
XmlDeclaration | yes* | no | no | no | no | no | no | no | no |
Element | yes | no | no | yes | no | no | no | no | yes*** |
Attribute | no | no | no | yes**** | no | no | no | no | no |
Text | no | no | no | yes | yes | no | no | no | yes |
CDATA | no | no | no | yes | no | no | no | no | yes*** |
Markup** | yes | no | no | yes | no | no | no | no | no |
EntityReference | no | no | no | yes | yes | no | no | no | yes |
* The XmlDeclaration node must be the first child of the Document node.
** Markup includes ProcessingInstruction and Comment nodes.
*** Element and CDATA nodes are only allowed in EntityReference nodes when the EntityReference node is not a child of an Attribute node.
**** Attributes are not children of an Element node. Attributes are contained inside an attribute collection that belongs to the Element node.
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { Sample test = new Sample(); } public Sample() { try { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre=\"novel\" publicationdate=\"1997\" " + " ISBN=\"1-861001-57-5\">" + " <title>Pride And Prejudice</title>" + " <author>" + " <first-name>Jane</first-name>" + " <last-name>Austen</last-name>" + " </author>" + " <price>24.95</price>" + "</book>"); XmlNode newElem=doc.CreateNode(XmlNodeType.Element, "pages", ""); newElem.InnerText = "290"; //add the new node to the document Console.WriteLine("Add the new element to the existing document..."); XmlElement root = doc.DocumentElement; root.AppendChild(newElem); Console.WriteLine("Display the modified xml document..."); Console.WriteLine(doc.OuterXml); } catch (Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } } }
public virtual XmlProcessingInstruction CreateProcessingInstruction( |
target
data
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); // Create a procesing instruction. XmlProcessingInstruction newPI; String PItext = "type='text/xsl' href='book.xsl'"; newPI = doc.CreateProcessingInstruction("xml-stylesheet", PItext); // Display the target and data information. Console.WriteLine("<?{0} {1}?>", newPI.Target, newPI.Data); // Add the processing instruction node to the document. doc.AppendChild(newPI); } }
public virtual XmlSignificantWhitespace CreateSignificantWhitespace( |
text
Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. To add the new object, you must explicitly call one of the node insert methods.
using System; using System.IO; using System.Xml; public class Sample { private XmlNode currNode; public static void Main() { Sample test = new Sample(); } public Sample() { try { XmlDocument doc = new XmlDocument(); doc.LoadXml("<!-- Sample XML fragment -->" + "<author xml:space=\"preserve\">" + "<first-name>Jane</first-name>"+ "<last-name>Austen</last-name>" + "</author>"); Console.WriteLine("InnerText before..."); Console.WriteLine(doc.DocumentElement.InnerText); //add whitespace currNode=doc.DocumentElement; XmlSignificantWhitespace sigws=doc.CreateSignificantWhitespace("\t"); currNode.InsertAfter(sigws, currNode.FirstChild); Console.WriteLine(); Console.WriteLine("InnerText after..."); Console.WriteLine(doc.DocumentElement.InnerText); } catch (Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } } }
text
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Create a new node and add it to the document. //The text node is the content of the price element. XmlElement elem = doc.CreateElement("price"); XmlText text = doc.CreateTextNode("19.95"); doc.DocumentElement.AppendChild(elem); doc.DocumentElement.LastChild.AppendChild(text); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
public virtual XmlWhitespace CreateWhitespace( |
text
Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. To add the new object, you must explicitly call one of the node insert methods.
using System; using System.IO; using System.Xml; public class Sample { private XmlNode currNode; public static void Main() { Sample test = new Sample(); } public Sample() { try { XmlDocument doc = new XmlDocument(); doc.LoadXml("<!-- Sample XML fragment -->" + "<author xml:space=\"preserve\">" + "<first-name>Jane</first-name>"+ "<last-name>Austen</last-name>" + "</author>"); Console.WriteLine("InnerText before..."); Console.WriteLine(doc.DocumentElement.InnerText); //add whitespace currNode=doc.DocumentElement; XmlWhitespace ws = doc.CreateWhitespace("\r\n"); currNode.InsertAfter(ws, currNode.FirstChild); Console.WriteLine(); Console.WriteLine("InnerText after..."); Console.WriteLine(doc.DocumentElement.InnerText); } catch (Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } } }
public virtual XmlDeclaration CreateXmlDeclaration( |
version
encoding
Note: If the XmlDocument is saved to either a TextWriter or an XmlTextWriter, this encoding value is discarded. Instead, the encoding of the TextWriter or the XmlTextWriter is used. This ensures that the XML written out can be read back using the correct encoding.
The value of the encoding attribute. This is the encoding that is used when you save the XmlDocument to a file or a stream; therefore, it must be set to a string supported by the Encoding class, otherwise XmlDocument.Save fails. If this is null or String.Empty, the Save method does not write an encoding attribute on the XML declaration and therefore the default encoding, UTF-8, is used.Note: If the XmlDocument is saved to either a TextWriter or an XmlTextWriter, this encoding value is discarded. Instead, the encoding of the TextWriter or the XmlTextWriter is used. This ensures that the XML written out can be read back using the correct encoding.
standalone
Exception Type | Condition |
---|---|
ArgumentException | The values of version or standalone are something other than the ones specified above. |
Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. To add the new object, you must explicitly call one of the node insert methods.
According to the W3C Extensible Markup Language (XML) 1.0 recommendation (www.w3.org/TR/1998/REC-xml-19980210), the XmlDeclaration node must be the first node in the document.This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Create an XML declaration. XmlDeclaration xmldecl; xmldecl = doc.CreateXmlDeclaration("1.0",null,null); //Add the new node to the document. XmlElement root = doc.DocumentElement; doc.InsertBefore(xmldecl, root); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
~XmlDocument(); |
public virtual XmlElement GetElementById( |
elementId
using System; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.Load("ids.xml"); //Get the first element with an attribute of type ID and value of A111. //This displays the node <Person SSN="A111" Name="Fred"/>. XmlElement elem = doc.GetElementById("A111"); Console.WriteLine( elem.OuterXml ); //Get the first element with an attribute of type ID and value of A222. //This displays the node <Person SSN="A222" Name="Tom"/>. elem = doc.GetElementById("A222"); Console.WriteLine( elem.OuterXml ); } }The example uses the file, ids.xml, as input.
<!DOCTYPE root [ <!ELEMENT root ANY> <!ELEMENT Person ANY> <!ELEMENT Customer EMPTY> <!ELEMENT Team EMPTY> <!ATTLIST Person SSN ID #REQUIRED> <!ATTLIST Customer id IDREF #REQUIRED > <!ATTLIST Team members IDREFS #REQUIRED>]> <root> <Person SSN='A111' Name='Fred'/> <Person SSN='A111'/> <Person SSN='A222' Name='Tom'/> <Customer id='A111'/> <Customer id='A222334444'/> <Team members='A222334444 A333445555'/> </root>
public virtual XmlNodeList GetElementsByTagName( |
name
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.Load("books.xml"); //Display all the book titles. XmlNodeList elemList = doc.GetElementsByTagName("title"); for (int i=0; i < elemList.Count; i++) { Console.WriteLine(elemList[i].InnerXml); } } }
public virtual XmlNodeList GetElementsByTagName( |
localName
namespaceURI
public IEnumerator GetEnumerator(); |
using System; using System.Collections; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.Load("books.xml"); Console.WriteLine("Display all the books..."); XmlNode root = doc.DocumentElement; IEnumerator ienum = root.GetEnumerator(); XmlNode book; while (ienum.MoveNext()) { book = (XmlNode) ienum.Current; Console.WriteLine(book.OuterXml); Console.WriteLine(); } } }
The example uses the file, books.xml, as input.
<?xml version='1.0'?> <!-- This file represents a fragment of a book store inventory database --> <bookstore> <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0"> <title>The Autobiography of Benjamin Franklin</title> <author> <first-name>Benjamin</first-name> <last-name>Franklin</last-name> </author> <price>8.99</price> </book> <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2"> <title>The Confidence Man</title> <author> <first-name>Herman</first-name> <last-name>Melville</last-name> </author> <price>11.99</price> </book> <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6"> <title>The Gorgias</title> <author> <name>Plato</name> </author> <price>9.99</price> </book> </bookstore>
public virtual int GetHashCode(); |
prefix
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book xmlns:bk='urn:samples' bk:ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); XmlNode root = doc.FirstChild; //Create a new attribute. string ns = root.GetNamespaceOfPrefix("bk"); XmlNode attr = doc.CreateNode(XmlNodeType.Attribute, "genre", ns); attr.Value = "novel"; //Add the attribute to the document. root.Attributes.SetNamedItem(attr); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
namespaceURI
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book xmlns:bk='urn:samples' bk:ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); XmlNode root = doc.FirstChild; //Create a new node. string prefix = root.GetPrefixOfNamespace("urn:samples"); XmlElement elem = doc.CreateElement(prefix, "style", "urn:samples"); elem.InnerText = "hardcover"; //Add the node to the document. root.AppendChild(elem); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
public Type GetType(); |
node
deep
Exception Type | Condition |
---|---|
InvalidOperationException | Calling this method on a node type which cannot be imported. |
Importing a node creates an XmlNode object owned by the importing document, with XmlNode.Name and XmlNode.NodeType identical to the source node. The new object also has the attributes related to namespaces ( XmlNode.Prefix, XmlNode.LocalName, and XmlNode.NamespaceURI).
Depending on the node type of the imported node and the value of the deep parameter, additional information is copied as appropriate. This method attempts to mirror the behavior expected if a fragment of XML or HTML source was copied from one document to another (recognizing that, in the XML case, the two documents may have different DTDs).
The following table describes the specific behavior for each XmlNodeType.
XmlNodeType | ImportNode(true) | ImportNode(false) |
---|---|---|
Attribute | The XmlAttribute.Specified property is set to true on the generated XmlAttribute . The descendants of the source XmlAttribute are recursively imported and the resulting nodes reassembled to form the corresponding subtree. | The parameter does not apply to XmlAttribute nodes; they always carry their children with them when imported. |
CData | Copies the node, including its data. | Copies the node, including its data. |
Comment | Copies the node, including its data. | Copies the node, including its data. |
DocumentFragment | The descendants of the source node are recursively imported and the resulting nodes reassembled to form the corresponding subtree. | An empty XmlDocumentFragment is generated. |
DocumentType | Copies the node, including its data.* | Copies the node, including its data.* |
Element | The descendants of the source element and its specified attribute nodes are recursively imported and the resulting nodes reassembled to form the corresponding subtree.Note: Default attributes are not copied. If the document being imported into defines default attributes for this element name, those are assigned. | Specified attribute nodes of the source element are imported, and the generated XmlAttribute nodes are attached to the generated XmlElement.Note: Default attributes are not copied. If the document being imported into defines default attributes for this element name, those are assigned. |
EntityReference | Because the source and destination documents could have the entities defined differently, this method only copies the XmlEntityReference node. The replacement text is not included. If the destination document has the entity defined, its value is assigned. | Because the source and destination documents could have the entities defined differently, this method only copies the XmlEntityReference node. The replacement text is not included. If the destination document has the entity defined, its value is assigned. |
ProcessingInstruction | Copies the target and data value from the imported node. | Copies the target and data value from the imported node. |
Text | Copies the node, including its data. | Copies the node, including its data. |
SignificantWhitespace | Copies the node, including its data. | Copies the node, including its data. |
Whitespace | Copies the node, including its data. | Copies the node, including its data. |
XmlDeclaration | Copies the target and data value from the imported node. | Copies the target and data value from the imported node. |
All other node types. | These node types cannot be imported. | These node types cannot be imported. |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<bookstore>" + "<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>" + "</bookstore>"); //Create another XmlDocument which holds a list of books. XmlDocument doc2 = new XmlDocument(); doc2.Load("books.xml"); //Import the last book node from doc2 into the original document. XmlNode newBook = doc.ImportNode(doc2.DocumentElement.LastChild, true); doc.DocumentElement.AppendChild(newBook); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }The example uses the file, books.xml, as input.
<?xml version='1.0'?> <!-- This file represents a fragment of a book store inventory database --> <bookstore> <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0"> <title>The Autobiography of Benjamin Franklin</title> <author> <first-name>Benjamin</first-name> <last-name>Franklin</last-name> </author> <price>8.99</price> </book> <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2"> <title>The Confidence Man</title> <author> <first-name>Herman</first-name> <last-name>Melville</last-name> </author> <price>11.99</price> </book> <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6"> <title>The Gorgias</title> <author> <name>Plato</name> </author> <price>9.99</price> </book> </bookstore>
newChild
refChild
Exception Type | Condition |
---|---|
InvalidOperationException | This node is of a type that does not allow children of the type of the newChild node. Or the node to insert is one of this node's ancestors. |
ArgumentException | The newChild was created from a different document than the one that created this node. The refChild is not a child of this node. This node is read-only. |
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); XmlNode root = doc.DocumentElement; //Create a new node. XmlElement elem = doc.CreateElement("price"); elem.InnerText="19.95"; //Add the node to the document. root.InsertAfter(elem, root.FirstChild); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
newChild
refChild
Exception Type | Condition |
---|---|
InvalidOperationException | The current node is of a type that does not allow children of the type of the newChild node. Or the node to insert is an ancestor of this node. |
ArgumentException | The newChild was created from a different document than the one that created this node. The refChild is not a child of this node. This node is read-only. |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); XmlNode root = doc.DocumentElement; //Create a new node. XmlElement elem = doc.CreateElement("price"); elem.InnerText="19.95"; //Add the node to the document. root.InsertBefore(elem, root.FirstChild); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
public virtual void Load( |
inStream
Exception Type | Condition |
---|---|
XmlException | There is a load or parse error in the XML. In this case, the document remains empty. |
This method is a Microsoft extension to the Document Object Model (DOM).
public virtual void Load( |
filename
Exception Type | Condition |
---|---|
XmlException | There is a load or parse error in the XML. In this case, the document remains empty. |
This method is a Microsoft extension to the Document Object Model (DOM).
public virtual void Load( |
txtReader
Exception Type | Condition |
---|---|
XmlException | There is a load or parse error in the XML. In this case, the document remains empty. |
This method is a Microsoft extension to the Document Object Model (DOM).
public virtual void Load( |
reader
Exception Type | Condition |
---|---|
XmlException | There is a load or parse error in the XML. In this case, the document remains empty. |
If the reader is already positioned on some node at depth "n", this method loads that node and all subsequent siblings up to the end tag that closes depth "n". This has the following results.
If the current node and its siblings look like the following:
<!--comment--><element1>one</element1><element2>two</element2>
Load throws an exception because a document cannot have two root level elements. If the current node and its siblings look like the following:
<!--comment--><?process
instruction?><!--comment--></endtag>
Load succeeds, but you have an incomplete DOM tree because there is no root level element. Before you save the document, you must add a root level element, otherwise XmlDocument.Save will throw an exception.
If the reader is positioned on a leaf node that is invalid for the root level of a document, for example a whitespace or attribute node, the reader continues to read until it is positioned on a node that can be used for the root. The document begins loading at this point.
This method does not do DTD or schema validation. If you want validation to occur, you need to pass an XmlValidatingReader, specify the appropriate XmlValidatingReader.ValidationType, and provide a XmlValidatingReader.ValidationEventHandler. You are then notified of all validation errors found during Load, and unless your ValidationEventHandler throws an exception to stop the process, the document will still be loaded.
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); //Load the the document with the last book node. XmlTextReader reader = new XmlTextReader("books.xml"); reader.WhitespaceHandling = WhitespaceHandling.None; reader.MoveToContent(); reader.Read(); reader.Skip(); //Skip the first book. reader.Skip(); //Skip the second book. doc.Load(reader); doc.Save(Console.Out); } }The example uses the file, books.xml, as input.
<?xml version='1.0'?> <!-- This file represents a fragment of a book store inventory database --> <bookstore> <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0"> <title>The Autobiography of Benjamin Franklin</title> <author> <first-name>Benjamin</first-name> <last-name>Franklin</last-name> </author> <price>8.99</price> </book> <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2"> <title>The Confidence Man</title> <author> <first-name>Herman</first-name> <last-name>Melville</last-name> </author> <price>11.99</price> </book> <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6"> <title>The Gorgias</title> <author> <name>Plato</name> </author> <price>9.99</price> </book> </bookstore>
public virtual void LoadXml( |
xml
Exception Type | Condition |
---|---|
XmlException | There is a load or parse error in the XML. In this case, the document remains empty. |
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Save the document to a file. doc.Save("data.xml"); } }
protected object MemberwiseClone(); |
public virtual void Normalize(); |
newChild
Exception Type | Condition |
---|---|
InvalidOperationException | This node is of a type that does not allow children of the type of the newChild node. Or the node to be added is one of this node's ancestors. |
ArgumentException | The newChild was created from a different document than the one that created this node. Or this node is read-only. |
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); XmlNode root = doc.DocumentElement; //Create a new node. XmlElement elem = doc.CreateElement("price"); elem.InnerText="19.95"; //Add the node to the document. root.PrependChild(elem); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
reader
Exception Type | Condition |
---|---|
InvalidOperationException | The reader is positioned on a node type that does not translate to a valid DOM node (for example, EndElement or EndEntity). |
If the reader is positioned on the start of an element, ReadNode reads all the attributes and any child nodes, up to and including the end tag of the current node. The XmlNode returned contains the sub-tree representing everything read. The reader is positioned immediately after the end tag.
ReadNode can also read attributes, but in this case it does not advance the reader to the next attribute. This allows you to write the following C# code:
XmlDocument doc = new XmlDocument(); while (reader.MoveToNextAttribute()) { XmlNode a = doc.ReadNode(reader); // Do some more processing. }
ReadNode does consume the attribute value though, which means after calling ReadNode on an attribute, XmlReader.ReadAttributeValue returns false.
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<bookstore>" + "<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>" + "</bookstore>"); //Create a reader. XmlTextReader reader = new XmlTextReader("cd.xml"); reader.MoveToContent(); //Move to the cd element node. //Create a node representing the cd element node. XmlNode cd = doc.ReadNode(reader); //Insert the new node into the document. doc.DocumentElement.AppendChild(cd); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }The example uses the file, cd.xml, as input.
<!-- sample CD --> <cd genre='alternative'> <title>Americana</title> <artist>Offspring</artist> </cd>
public virtual void RemoveAll(); |
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); XmlNode root = doc.DocumentElement; //Remove all attribute and child nodes. root.RemoveAll(); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
oldChild
Exception Type | Condition |
---|---|
ArgumentException | The oldChild is not a child of this node. Or this node is read-only. |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); XmlNode root = doc.DocumentElement; //Remove the title element. root.RemoveChild(root.FirstChild); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
newChild
oldChild
Exception Type | Condition |
---|---|
InvalidOperationException | This node is of a type that does not allow children of the type of the newChild node. Or the node to put in is one of this node's ancestors. |
ArgumentException | The newChild was created from a different document than the one that created this node. This node is read-only. The oldChild is not a child of this node. |
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); XmlNode root = doc.DocumentElement; //Create a new title element. XmlElement elem = doc.CreateElement("title"); elem.InnerText="The Handmaid's Tale"; //Replace the title element. root.ReplaceChild(elem, root.FirstChild); Console.WriteLine("Display the modified XML..."); doc.Save(Console.Out); } }
public virtual void Save( |
outStream
Exception Type | Condition |
---|---|
XmlException | The operation would not result in a well formed XML document (for example, no document element or duplicate XML declarations). |
When the document is saved, xmlns attributes are generated to persist the node identity (LocalName + NamespaceURI) correctly. For example, the following C# code
XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("item","urn:1")); doc.Save(Console.Out);
generates this xmls attribute:
<item xmls="urn:1"/>
This method is a Microsoft extension to the Document Object Model (DOM).
public virtual void Save( |
filename
Exception Type | Condition |
---|---|
XmlException | The operation would not result in a well formed XML document (for example, no document element or duplicate XML declarations). |
When the document is saved, xmlns attributes are generated to persist the node identity (LocalName + NamespaceURI) correctly. For example, the following C# code
XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("item","urn:1")); doc.Save(Console.Out);
generates this xmls attribute:
<item xmls="urn:1"/>
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { private const String saved_Doc = "output.xml"; public static void Main() { Sample test = new Sample(); } public Sample() { try { XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre=\"novel\" publicationdate=\"1997\" " + " ISBN=\"1-861001-57-5\">" + " <title>Pride And Prejudice</title>" + " <author>" + " <first-name>Jane</first-name>" + " <last-name>Austen</last-name>" + " </author>" + " <price>24.95</price>" + "</book>"); XmlElement newElem = doc.CreateElement("availability"); Console.WriteLine("Create some attributes and then add them to the element..."); XmlAttribute newAttr = doc.CreateAttribute("outofstock"); XmlAttribute newAttr1 = doc.CreateAttribute("style"); newElem.SetAttributeNode(newAttr); newElem.SetAttribute("outofstock", "", "false"); newElem.SetAttributeNode("style",""); newElem.SetAttribute("style", "hardcover"); //add the new element to the document XmlElement root = doc.DocumentElement; root.AppendChild(newElem); //save the output to a file doc.Save(saved_Doc); Console.WriteLine(); Console.WriteLine("Updated XML document saved in {0}", saved_Doc); } catch (Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } } }
public virtual void Save( |
writer
Exception Type | Condition |
---|---|
XmlException | The operation would not result in a well formed XML document (for example, no document element or duplicate XML declarations). |
This method is a Microsoft extension to the Document Object Model (DOM).
public virtual void Save( |
w
Exception Type | Condition |
---|---|
XmlException | The operation would not result in a well formed XML document (for example, no document element or duplicate XML declarations). |
The encoding on the XmlWriter determines the encoding that is written out (The encoding of the XmlDeclaration node is also replaced by the encoding of the TextWriter). If there was no encoding specified on the XmlWriter, the XmlDocument is saved without an encoding attribute.
When the document is saved, xmlns attributes are generated to persist the node identity (LocalName + NamespaceURI) correctly. For example, the following C# code
XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("item","urn:1")); doc.Save(Console.Out);
generates this xmls attribute:
<item xmls="urn:1"/>
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Save the document to a file. doc.Save("data.xml"); } }
public XmlNodeList SelectNodes( |
xpath
Exception Type | Condition |
---|---|
XPathException | The XPath expression contains a prefix. |
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.Load("booksort.xml"); XmlNodeList nodeList; XmlNode root = doc.DocumentElement; nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']"); //Change the price on the books. foreach (XmlNode book in nodeList) { book.LastChild.InnerText="15.95"; } Console.WriteLine("Display the modified XML document...."); doc.Save(Console.Out); } }
The example uses the file, booksort.xml, as input.
<?xml version="1.0"?> <!-- a fragment of a book store inventory database --> <bookstore xmlns:bk="urn:samples"> <book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8"> <title>Pride And Prejudice</title> <author> <first-name>Jane</first-name> <last-name>Austen</last-name> </author> <price>24.95</price> </book> <book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1"> <title>The Handmaid's Tale</title> <author> <first-name>Margaret</first-name> <last-name>Atwood</last-name> </author> <price>29.95</price> </book> <book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6"> <title>Emma</title> <author> <first-name>Jane</first-name> <last-name>Austen</last-name> </author> <price>19.95</price> </book> <book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3"> <title>Sense and Sensibility</title> <author> <first-name>Jane</first-name> <last-name>Austen</last-name> </author> <price>19.95</price> </book> </bookstore>
public XmlNodeList SelectNodes( |
xpath
nsmgr
Exception Type | Condition |
---|---|
XPathException | The XPath expression contains a prefix which is not defined in the XmlNamespaceManager. |
For example, if you had the following XML:
<bookstore xmlns="http://www.lucernepublishing.com"> <book> <title>Pride And Prejudice</title> </book> </bookstore>
The following C# code selects all book nodes:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("ab", "http://www.lucernepublishing.com"); XmlNodeList nodelist = doc.SelectNodes("//ab:book", nsmgr);
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.Load("booksort.xml"); //Create an XmlNamespaceManager for resolving namespaces. XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("bk", "urn:samples"); //Select and display the value of all the ISBN attributes. XmlNodeList nodeList; XmlElement root = doc.DocumentElement; nodeList = root.SelectNodes("/bookstore/book/@bk:ISBN", nsmgr); foreach (XmlNode isbn in nodeList){ Console.WriteLine(isbn.Value); } } }The example uses the file, booksort.xml, as input.
<?xml version="1.0"?> <!-- a fragment of a book store inventory database --> <bookstore xmlns:bk="urn:samples"> <book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8"> <title>Pride And Prejudice</title> <author> <first-name>Jane</first-name> <last-name>Austen</last-name> </author> <price>24.95</price> </book> <book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1"> <title>The Handmaid's Tale</title> <author> <first-name>Margaret</first-name> <last-name>Atwood</last-name> </author> <price>29.95</price> </book> <book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6"> <title>Emma</title> <author> <first-name>Jane</first-name> <last-name>Austen</last-name> </author> <price>19.95</price> </book> <book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3"> <title>Sense and Sensibility</title> <author> <first-name>Jane</first-name> <last-name>Austen</last-name> </author> <price>19.95</price> </book> </bookstore>
xpath
Exception Type | Condition |
---|---|
XPathException | The XPath expression contains a prefix. |
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.Load("booksort.xml"); XmlNode book; XmlNode root = doc.DocumentElement; book=root.SelectSingleNode("descendant::book[author/last-name='Austen']"); //Change the price on the book. book.LastChild.InnerText="15.95"; Console.WriteLine("Display the modified XML document...."); doc.Save(Console.Out); } }The example uses the file, booksort.xml, as input.
<?xml version="1.0"?> <!-- a fragment of a book store inventory database --> <bookstore xmlns:bk="urn:samples"> <book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8"> <title>Pride And Prejudice</title> <author> <first-name>Jane</first-name> <last-name>Austen</last-name> </author> <price>24.95</price> </book> <book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1"> <title>The Handmaid's Tale</title> <author> <first-name>Margaret</first-name> <last-name>Atwood</last-name> </author> <price>29.95</price> </book> <book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6"> <title>Emma</title> <author> <first-name>Jane</first-name> <last-name>Austen</last-name> </author> <price>19.95</price> </book> <book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3"> <title>Sense and Sensibility</title> <author> <first-name>Jane</first-name> <last-name>Austen</last-name> </author> <price>19.95</price> </book> </bookstore>
public XmlNode SelectSingleNode( |
xpath
nsmgr
Exception Type | Condition |
---|---|
XPathException | The XPath expression contains a prefix which is not defined in the XmlNamespaceManager. |
For example, if you had the following XML:
<bookstore xmlns="http://www.lucernepublishing.com"> <book> <title>Pride And Prejudice</title> </book> </bookstore>
The following C# code selects the first book node:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("ab", "http://www.lucernepublishing.com"); XmlNode book = doc.SelectSingleNode("//ab:book", nsmgr);
This method is a Microsoft extension to the Document Object Model (DOM).
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.Load("booksort.xml"); //Create an XmlNamespaceManager for resolving namespaces. XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("bk", "urn:samples"); //Select the book node with the matching attribute value. XmlNode book; XmlElement root = doc.DocumentElement; book = root.SelectSingleNode("descendant::book[@bk:ISBN='1-861001-57-6']", nsmgr); Console.WriteLine(book.OuterXml); } }The example uses the file, booksort.xml, as input.
<?xml version="1.0"?> <!-- a fragment of a book store inventory database --> <bookstore xmlns:bk="urn:samples"> <book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8"> <title>Pride And Prejudice</title> <author> <first-name>Jane</first-name> <last-name>Austen</last-name> </author> <price>24.95</price> </book> <book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1"> <title>The Handmaid's Tale</title> <author> <first-name>Margaret</first-name> <last-name>Atwood</last-name> </author> <price>29.95</price> </book> <book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6"> <title>Emma</title> <author> <first-name>Jane</first-name> <last-name>Austen</last-name> </author> <price>19.95</price> </book> <book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3"> <title>Sense and Sensibility</title> <author> <first-name>Jane</first-name> <last-name>Austen</last-name> </author> <price>19.95</price> </book> </bookstore>
feature
version
Feature | Version |
---|---|
XML | 1.0 |
XML | 2.0 |
public virtual string ToString(); |
public override void WriteContentTo( |
xw
The XmlDeclaration.Encoding property determines the encoding that is written out. If the Encoding property does not have a value, the XmlDocument is written out without an encoding attribute.
public static void WriteXml( XmlDocument doc ) { XmlTextWriter writer = new XmlTextWriter(Console.Out); writer.Formatting = Formatting.Indented; doc.WriteContentTo( writer ); writer.Flush(); Console.WriteLine(); }
public override void WriteTo( |
w
The XmlDeclaration.Encoding property determines the encoding that is written out. If the Encoding property does not have a value, the XmlDocument is written out without an encoding attribute.
public static void WriteXml( XmlDocument doc ) { XmlTextWriter writer = new XmlTextWriter(Console.Out); writer.Formatting = Formatting.Indented; doc.WriteTo( writer ); writer.Flush(); Console.WriteLine(); }
public event XmlNodeChangedEventHandler NodeChanged;
|
All nodes created by this document, whether or not they have been inserted into the document, are included in this event.
public event XmlNodeChangedEventHandler NodeChanging;
|
All nodes created by this document, whether or not they have been inserted into the document, are included in this event.
public event XmlNodeChangedEventHandler NodeInserted;
|
public event XmlNodeChangedEventHandler NodeInserting;
|
All nodes created by this document, whether or not they have been inserted into the document, are included in this event.
public event XmlNodeChangedEventHandler NodeRemoved;
|
public event XmlNodeChangedEventHandler NodeRemoving;
|
All nodes created by this document, whether or not they have been inserted into the document, are included in this event.