空白xmlns =""在新的XmlElement上设置InnerXml之后 [英] Blank xmlns="" after setting InnerXml on new XmlElement

查看:44
本文介绍了空白xmlns =""在新的XmlElement上设置InnerXml之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了与此类似的问题:

I came across a problem similar to this:

>如何防止NET的XmlDocument输出?

除了我要创建一个新节点,然后将其InnerXml属性设置为XML字符串.

Except I'm creating a new node and then setting it's InnerXml property to a string of 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()时遇到了相同的问题.

According to the MSDN, the parsing is done in the current namespace context. I expected the current namespace context would have been the default namespace for not only newElement but all imported child nodes. I have experienced the same issue using CreateDocumentFragment().

在导入xml字符串时,是否有任何方法可以防止newElement下的子节点显示为空的命名空间?

Is there any way to prevent the child node immediately under newElement from showing up with an empty Namespace when importing a string of xml?

推荐答案

语句:

解析是在当前名称空间上下文中完成的.

The parsing is done in the current namespace context.

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

means that any namespace prefixes that your XML string might contain will be interpreted in the context of the namespace prefixes that the document defines.

这将导致以下情况起作用:

This causes that the following thing works:

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>

但是,没有前缀的节点在定义上没有特定的名称空间.它们位于默认名称空间中.

However, nodes that don't have a prefix are in no particular namespace by definition. They are in the default namespace.

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

There is no way you can influence the default namespace when setting InnerXml. It will always be assumed that the default namespace is the empty namespace.

这篇关于空白xmlns =""在新的XmlElement上设置InnerXml之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆