我试图在 CreateElement 方法中转义冒号。例如,我想更改以下内容:
$node = $xmldoc.CreateElement("test:example")
给我一个如下所示的节点:
<test:example>
但不幸的是我只得到这个:
<example>
有关此方法的 Microsoft 文档指出,冒号之前的任何内容都用作前缀属性,其余部分是 LocalName。前缀没有出现在节点中,因此我想做一个解决方法,输出冒号,但不将第一部分分类为前缀。
我尝试使用 baskslash 来转义它,并且通常会寻找不同的方法在其他线程上执行此操作,但通常答案是避免出现必须首先转义字符的情况。但我无法避免它,因为我对总体预期的 XML 结构没有发言权。
Martin Honnen 提供了关键点:
如果您在元素名称中使用命名空间 prefix,则必须向 System.Xml.XmlDocument.CreateElement()
调用提供相应的命名空间URI,作为第二个参数:
$node = $xmldoc.CreateElement('test:example', 'https://example.org')
或者,使用单独指定前缀的重载:
$node = $xmldoc.CreateElement('test', 'example', 'https://example.org')
如果您忽略传递名称空间 URI,您的前缀 (
test:
) 会被悄悄地忽略并从元素名称中删除 - 即使指定的前缀是在所有者文档中定义的。
独立的示例:
# Create a sample document that declares a 'test' same prefix with
# a sample namespace URI.
$sampleNamespaceUri = 'https://example.org'
$doc = [xml] "<foo xmlns:test=`"$sampleNamespaceUri`"/>"
# Create the new element.
# NOTE:
# * Even though the owner document knows prefix 'test', you must still
# pass the corresponding namespace URI explcitly.
# * If the URI *differs* from the one associated with 'test' in the owner
# document, the prefix will be *redefined as part your element*, i.e.
# a 'xmlns:test="<different-URI>' attribute will be added to it.
$node = $doc.CreateElement('test:me', $sampleNamespaceUri)
# Append the element as a child node.
$null = $doc.foo.AppendChild($node)
# Print the modified document's XML text.
$doc.OuterXml
输出(漂亮):
<foo xmlns:test="https://example.org">
<test:me />
</foo>
注意:如果命名空间 URI 不匹配,您会看到类似以下内容 - 请注意新插入元素级别的前缀的重新定义:
<foo xmlns:test="https://example.org">
<test:me xmlns:test="https://different.example.org" />
</foo>