XPathNavigator.CreateAttributes 方法

定义

返回一个 XmlWriter 对象,该对象用于在当前元素上创建一个新属性。

C#
public virtual System.Xml.XmlWriter CreateAttributes();

返回

XmlWriter 对象,用于在当前元素上创建新属性。

例外

XPathNavigator 未定位在元素节点上。

示例

在以下示例中,使用从 discount 方法返回的 currency 对象在 price 文件中第一个 book 元素的 contosoBooks.xml 子元素上创建新的 XmlWriterCreateAttributes 属性。

C#
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");

XmlWriter attributes = navigator.CreateAttributes();

attributes.WriteAttributeString("discount", "1.00");
attributes.WriteAttributeString("currency", "USD");
attributes.Close();

navigator.MoveToParent();
Console.WriteLine(navigator.OuterXml);

该示例使用 contosoBooks.xml 文件作为输入。

XML
<?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>  

注解

以下是使用 CreateAttributes 方法时要考虑的重要注意事项。

  • XPathNavigator当 定位在元素上时,由 XPathNavigator 方法创建的新属性将放置在当前元素的属性列表的末尾。

  • 在调用 对象的 方法XmlWriter之前,Close不会插入新属性。

  • 如果指定的命名空间前缀为 String.Emptynull,则新属性的命名空间 URI 的前缀将从范围内的当前命名空间获取。 如果当前范围中没有分配给指定命名空间 URI 的命名空间前缀,则自动生成命名空间前缀。 例如,若要在文件的默认命名空间 contosoBooks.xml 中的元素上创建新属性, (xmlns="http://www.contoso.com/books") ,请同时为命名空间前缀和命名空间 URI 参数指定 nullString.Empty 。 将 http://www.contoso.com/books 指定为命名空间 URI 参数将导致 CreateAttribute 方法自动生成新属性的命名空间前缀。

  • 如果创建的新属性是一个命名空间节点,该节点与元素上的命名空间声明冲突,可能是因为所选命名空间前缀由同一范围内的另一个命名空间声明使用,或者因为所选的前缀与元素的前缀相同,但绑定到不同的命名空间 URI,则会引发异常。

  • XmlWriter返回的对象只能用于创建属性。 调用其他 XmlWriter 不创建属性的对象方法将引发异常。

  • 方法 CreateAttributes 不影响 的位置 XPathNavigator

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1