gpt4 book ai didi

.net - 在新 XmlElement 上设置 InnerXml 后空白 xmlns =""

转载 作者:行者123 更新时间:2023-12-05 03:11:41 26 4
gpt4 key购买 nike

我遇到过类似的问题:

How to prevent blank xmlns attributes in output from .NET's XmlDocument?

除非我正在创建一个新节点,然后将其 InnerXml 属性设置为一个 XML 字符串。

    Dim ns As String = "http://test"
Dim doc As XmlDocument = New XmlDocument
doc.LoadXml(String.Format("<data xmlns=""{0}""></data>", ns))

Dim newElement As XmlElement = doc.CreateElement("new", ns)
newElement.InnerXml = "<person><name>Joe</name></person>"

Dim result As String = newElement.OuterXml

我期望的是:

<data xmlns="http://test">
<new>
<person>
<name>Joe</name>
</person>
</new>
</data>

它实际创建了什么:

<data xmlns="http://test">
<new>
<person xmlns="">
<name>Joe</name>
</person>
</new>
</data>

根据MSDN ,解析是在当前命名空间上下文中完成的。我预计当前命名空间上下文不仅是 newElement 的默认命名空间,而且是所有导入的子节点的默认命名空间。我在使用 CreateDocumentFragment() 时遇到过同样的问题。

有什么方法可以防止在导入一串xml时紧接在newElement下的子节点出现空的Namespace吗?

最佳答案

声明:

The parsing is done in the current namespace context.

意味着您的 XML 字符串可能包含的任何 namespace 前缀都将在文档定义的 namespace 前缀的上下文中进行解释。

这导致以下事情起作用:

Const ns As String = "http://test"
Const ns_foo As String = "http://www.example.com"

Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml(String.Format("<data xmlns=""{0}"" xmlns:foo=""{1}""></data>", ns, ns_foo))

Dim newElement As XmlElement = doc.CreateElement("new", ns)
doc.DocumentElement.AppendChild(newElement)

newElement.InnerXml = "<foo:person><foo:name>Joe</foo:name></foo:person>"

结果

<data xmlns:foo="http://www.example.com" xmlns="http://test">
<new>
<foo:person>
<foo:name>Joe</foo:name>
</foo:person>
</new>
</data>

但是,没有前缀的节点根据定义不在特定的命名空间中。它们位于默认命名空间

在设置 InnerXml 时,您无法影响默认命名空间。始终假定默认命名空间是空命名空间。

关于.net - 在新 XmlElement 上设置 InnerXml 后空白 xmlns ="",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36338140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com