【问题标题】:How to create XML with declared namespace?如何使用声明的命名空间创建 XML?
【发布时间】:2016-04-24 02:22:40
【问题描述】:

我正在使用 java 创建一个 xml 请求。 我是使用 java 创建 xmls 的新手。

代码如下:

Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("UserRequest");
            rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ns0", "https://com.user.req");
            rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            doc.appendChild(rootElement);

            // user element
            Element user = doc.createElement("User");
            rootElement.appendChild(user);

            // userAttributes element
            Element userAttr = doc.createElement("UserAttributes");
            rootElement.appendChild(userAttr);


            // name elements
            Element name = doc.createElement("Name");
            name.appendChild(doc.createTextNode("hello"));
            userAttr.appendChild(name);
            // value elements
            Element value = doc.createElement("Value");
            name.appendChild(doc.createTextNode("dude"));
            userAttr.appendChild(value);

预期输出:

<?xml version="1.0" encoding="UTF-8"?>
<UserRequest 
xmlns:ns0="https://com.user.req" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:type="ns0:UserRequest">
  <User/>
  <UserAttributes>
    <Name>hello</Name>
    <Value>dude</Value>
  </UserAttributes>
</UserRequest>

生成的输出:

<?xml version="1.0" encoding="UTF-8"?>
<UserRequest 
xmlns:ns0="https://com.user.req" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

  <User/>
  <UserAttributes>
    <Name>hello</Name>
    <Value>dude</Value>
  </UserAttributes>
</UserRequest>

如何获得正确的命名空间(如预期部分所示)。

【问题讨论】:

    标签: java xml namespaces


    【解决方案1】:

    您生成的输出中的命名空间没有任何问题。然而,这是一个意外......你正在使用 setAttributeNS() 做一些不该做的事情。

    阅读 XML 命名空间声明和命名空间前缀。这比试图逐点解释为什么你没有得到你所期望的要容易得多。例如,xmlns 不是命名空间前缀,xsi:type 不是命名空间。

    不要像普通属性一样尝试创建所需的命名空间声明,而是删除这两行

    rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/",
            "xmlns:ns0", "https://com.user.req");
    rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/",
            "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    

    改为使用

    rootElement.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
            "xsi:type", "ns0:UserRequest");
    

    除了ns0 命名空间前缀声明之外,这应该会为您提供大部分预期输出。它不会生成,因为您没有在任何元素或属性上使用 ns0。你的意思是有

    <ns0:UserRequest ...
    

    在您的预期输出中?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多