使用 XPathNavigator 移除 XML 数据Remove XML Data using XPathNavigator

XPathNavigator 类提供一组方法用于移除 XML 文档中的节点和值。The XPathNavigator class provides a set of methods used to remove nodes and values from an XML document. 要使用这些方法,XPathNavigator 对象必须可编辑,即其 CanEdit 属性必须为 trueIn order to use these methods, the XPathNavigator object must be editable, that is, its CanEdit property must be true.

可以编辑 XML 文档的 XPathNavigator 对象由 CreateNavigator 类的 XmlDocument 方法创建。XPathNavigator objects that can edit an XML document are created by the CreateNavigator method of the XmlDocument class. XPathNavigator 类创建的 XPathDocument 对象是只读的,如果尝试使用由 XPathNavigator 对象创建的 XPathDocument 对象的编辑方法,将引发 NotSupportedExceptionXPathNavigator objects created by the XPathDocument class are read-only and any attempt to use the editing methods of an XPathNavigator object created by an XPathDocument object results in a NotSupportedException.

若要详细了解如何创建可编辑 XPathNavigator 对象,请参阅使用 XPathDocument 和 XmlDocument 读取 XML 数据For more information about creating editable XPathNavigator objects, see Reading XML Data using XPathDocument and XmlDocument.

移除节点Removing Nodes

XPathNavigator 类提供 DeleteSelf 方法来移除 XML 文档中的节点。The XPathNavigator class provides the DeleteSelf method to remove nodes from an XML document.

移除节点Removing a Node

XPathNavigator 类提供 DeleteSelf 方法来删除 XML 文档中 XPathNavigator 对象当前所处的节点。The XPathNavigator class provides the DeleteSelf method to delete the current node an XPathNavigator object is currently positioned on from an XML document.

使用 DeleteSelf 方法删除了某个节点之后,该节点无法再从 XmlDocument 对象的根节点访问。After a node has been deleted using the DeleteSelf method, it is no longer reachable from the root of the XmlDocument object. 节点删除之后,XPathNavigator 将位于所删除节点的父节点。After a node has been deleted, the XPathNavigator is positioned on the parent node of the deleted node.

删除操作不会影响位于所删除节点上的任何 XPathNavigator 对象的位置。A delete operation doesn't affect the position of any XPathNavigator object positioned on the deleted node. 这些 XPathNavigator 对象可以在已删除的子树内移动,在这方面看是有效的,但是不能使用 XPathNavigator 类常规的节点集浏览方法移至主节点树。These XPathNavigator objects are valid in the sense that they can move within the deleted subtree, but cannot be moved to the main node tree using the regular node set navigation methods of the XPathNavigator class.

备注

MoveTo 类的 XPathNavigator 方法可以用于将这些 XPathNavigator 对象移回主节点树,或从主节点树移至已删除的子树。The MoveTo method of the XPathNavigator class can be used to move these XPathNavigator objects back into the main node tree, or from the main node tree to the deleted subtree.

在以下示例中,price 文件的第一个 book 元素的 contosoBooks.xml 元素使用 DeleteSelf 方法删除。In the following example, the price element of the first book element of the contosoBooks.xml file is deleted using the DeleteSelf method. XPathNavigator 元素删除之后,price 对象的位置位于父级的 book 元素上。The position of the XPathNavigator object after the price element is deleted is on the parent book element.

Dim document As XmlDocument = New XmlDocument()  
document.Load("contosoBooks.xml")  
Dim navigator As XPathNavigator = document.CreateNavigator()  
  
navigator.MoveToChild("bookstore", "http://www.contoso.com/books")  
navigator.MoveToChild("book", "http://www.contoso.com/books")  
navigator.MoveToChild("price", "http://www.contoso.com/books")  
  
navigator.DeleteSelf()  
  
Console.WriteLine("Position after delete: {0}", navigator.Name)  
Console.WriteLine(navigator.OuterXml)  
XmlDocument document = new XmlDocument();  
document.Load("contosoBooks.xml");  
XPathNavigator navigator = document.CreateNavigator();  
  
navigator.MoveToChild("bookstore", "http://www.contoso.com/books");  
navigator.MoveToChild("book", "http://www.contoso.com/books");  
navigator.MoveToChild("price", "http://www.contoso.com/books");  
  
navigator.DeleteSelf();  
  
Console.WriteLine("Position after delete: {0}", navigator.Name);  
Console.WriteLine(navigator.OuterXml);  

该示例使用 contosoBooks.xml 文件作为输入。The example takes the contosoBooks.xml file as an input.

<?xml version="1.0" encoding="utf-8" ?>
<bookstore xmlns="http://www.contoso.com/books">
    <book genre="autobiography" publicationdate="1981-03-22" 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-11-17" 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-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
            <name>Plato</name>
        </author>
        <price>9.99</price>
    </book>
</bookstore>

移除属性节点Removing an Attribute Node

属性节点使用 DeleteSelf 方法从 XML 文档中移除。Attribute nodes are removed from an XML document using the DeleteSelf method.

属性节点删除之后,无法再从 XmlDocument 对象的根节点中访问,XPathNavigator 对象将位于父元素上。After an attribute node has been deleted, it is no longer reachable from the root node of an XmlDocument object and the XPathNavigator object is positioned on the parent element.

默认属性Default Attributes

无论用于移除属性的方法是什么,当移除在 XML 文档的 DTD 或 XML 架构中定义为默认属性的属性时有特殊限制。Regardless of the method used to remove attributes, there are special limitations on removing attributes that are defined as default attributes in the DTD or XML Schema for the XML document. 除非同时移除了默认属性所属的元素,否则不能移除默认属性。Default attributes cannot be removed unless the element they belong to is also removed. 对于声明了默认属性的元素,默认属性始终存在,因此,删除默认属性将使替换属性插入元素并初始化为所声明的默认值。Default attributes are always present for elements that have default attributes declared, and as a result, deleting a default attribute results in a replacement attribute being inserted into the element and initialized to the default value that was declared.

移除值Removing Values

XPathNavigator 类提供 SetValueSetTypedValue 方法来移除 XML 文档中非类型化的和类型化的值。The XPathNavigator class provides the SetValue and SetTypedValue methods to remove untyped and typed values from an XML document.

移除非类型化的值Removing Untyped Values

SetValue 方法只需将作为参数传递的非类型化的 string 值作为 XPathNavigator 对象当前所处的节点的值插入。The SetValue method simply inserts the untyped string value passed as a parameter as the value of the node the XPathNavigator object is currently positioned on. 如果将空字符串传递给 SetValue 方法,将移除当前节点的值。Passing an empty string to the SetValue method removes the value of the current node.

以下示例使用 price 方法移除 book 文件中第一个 contosoBooks.xml 元素的 SetValue 元素的值。The following example removes the value of the price element of the first book element in the contosoBooks.xml file using the SetValue method.

Dim document As XmlDocument = New XmlDocument()  
document.Load("contosoBooks.xml")  
Dim navigator As XPathNavigator = document.CreateNavigator()  
  
navigator.MoveToChild("bookstore", "http://www.contoso.com/books")  
navigator.MoveToChild("book", "http://www.contoso.com/books")  
navigator.MoveToChild("price", "http://www.contoso.com/books")  
  
navigator.SetValue("")  
  
navigator.MoveToRoot()  
Console.WriteLine(navigator.OuterXml)  
XmlDocument document = new XmlDocument();  
document.Load("contosoBooks.xml");  
XPathNavigator navigator = document.CreateNavigator();  
  
navigator.MoveToChild("bookstore", "http://www.contoso.com/books");  
navigator.MoveToChild("book", "http://www.contoso.com/books");  
navigator.MoveToChild("price", "http://www.contoso.com/books");  
  
navigator.SetValue("");  
  
navigator.MoveToRoot();  
Console.WriteLine(navigator.OuterXml);  

该示例使用 contosoBooks.xml 文件作为输入。The example takes the contosoBooks.xml file as an input.

<?xml version="1.0" encoding="utf-8" ?>
<bookstore xmlns="http://www.contoso.com/books">
    <book genre="autobiography" publicationdate="1981-03-22" 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-11-17" 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-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
            <name>Plato</name>
        </author>
        <price>9.99</price>
    </book>
</bookstore>

移除类型化的值Removing Typed Values

如果节点的类型为 W3C XML 架构的简单类型,在设置值之前,将针对简单类型的各个方面检查通过 SetTypedValue 方法插入的新值。When the type of a node is a W3C XML Schema simple type, the new value inserted by the SetTypedValue method is checked against the facets of the simple type before the value is set. 如果新值不符合节点的类型(例如在类型为 -1 的元素上设置值 xs:positiveInteger),将引发异常。If the new value is not valid according to the type of the node (for example, setting a value of -1 on an element whose type is xs:positiveInteger), it results in an exception. SetTypedValue 方法也不能作为参数传递 nullThe SetTypedValue method also cannot be passed null as a parameter. 因此,移除类型化节点的值必须符合节点的架构类型。As a result removing the value of a typed node must comply with the schema type of the node.

以下示例使用 price 方法移除 book 文件中第一个 contosoBooks.xml 元素的 SetTypedValue 元素的值,方法是将值设置为 0The following example removes the value of the price element of the first book element in the contosoBooks.xml file using the SetTypedValue method by setting the value to 0. 节点的值未移除,但是图书的价格已根据 xs:decimal 的数据类型移除。The value of the node is not removed, but the price of the book has been removed according to its data type of xs:decimal.

Dim settings As XmlReaderSettings = New XmlReaderSettings()  
settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")  
settings.ValidationType = ValidationType.Schema  
  
Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings)  
  
Dim document As XmlDocument = New XmlDocument()  
document.Load(reader)  
Dim navigator As XPathNavigator = document.CreateNavigator()  
  
navigator.MoveToChild("bookstore", "http://www.contoso.com/books")  
navigator.MoveToChild("book", "http://www.contoso.com/books")  
navigator.MoveToChild("price", "http://www.contoso.com/books")  
  
navigator.SetTypedValue(0)  
  
navigator.MoveToRoot()  
Console.WriteLine(navigator.OuterXml)  
XmlReaderSettings settings = new XmlReaderSettings();  
settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");  
settings.ValidationType = ValidationType.Schema;  
  
XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);  
  
XmlDocument document = new XmlDocument();  
document.Load(reader);  
XPathNavigator navigator = document.CreateNavigator();  
  
navigator.MoveToChild("bookstore", "http://www.contoso.com/books");  
navigator.MoveToChild("book", "http://www.contoso.com/books");  
navigator.MoveToChild("price", "http://www.contoso.com/books");  
  
navigator.SetTypedValue(0);  
  
navigator.MoveToRoot();  
Console.WriteLine(navigator.OuterXml);  

命名空间节点Namespace Nodes

命名空间节点不能从 XmlDocument 对象中删除。Namespace nodes cannot be deleted from an XmlDocument object. 如果尝试使用 DeleteSelf 方法删除命名空间节点,将引发异常。Attempts to delete namespace nodes using the DeleteSelf method results in an exception.

InnerXml 和 OuterXml 属性The InnerXml and OuterXml Properties

InnerXml 类的 OuterXmlXPathNavigator 属性更改 XPathNavigator 对象当前所处的节点的 XML 标记。The InnerXml and OuterXml properties of the XPathNavigator class change the XML markup of the nodes an XPathNavigator object is currently positioned on.

InnerXml 属性更改 XPathNavigator 对象当前所处的子节点以及给定 XML string 的已分析内容的 XML 标记。The InnerXml property changes the XML markup of the child nodes an XPathNavigator object is currently positioned on with the parsed contents of the given XML string. 同样,OuterXml 属性更改 XPathNavigator 对象当前所处的子节点以及当前节点本身的 XML 标记。Similarly, the OuterXml property changes the XML markup of the child nodes an XPathNavigator object is currently positioned on as well as the current node itself.

除了本主题中所述的方法之外,InnerXmlOuterXml 属性也可以用于移除 XML 文档中的节点和值。In addition to the methods described in this topic, the InnerXml and OuterXml properties can be used to remove nodes and values from an XML document. 若要详细了解如何使用 InnerXmlOuterXml 属性修改节点,请参阅使用 XPathNavigator 修改 XML 数据主题。For more information about using the InnerXml and OuterXml properties to modify nodes, see the Modify XML Data using XPathNavigator topic.

保存 XML 文档Saving an XML Document

使用 XmlDocument 类的方法保存本主题中所述的方法对 XmlDocument 对象的更改。Saving changes made to an XmlDocument object as the result of the methods described in this topic is performed using the methods of the XmlDocument class. 若要详细了解如何保存对 XmlDocument 对象所做的更改,请参阅保存和编写文档For more information about saving changes made to an XmlDocument object, see Saving and Writing a Document.

请参阅See also