Java XML创建没有命名空间的片段/元素

时间:2015-05-15 13:24:27

标签: java xml xml-namespaces

我正在尝试使用org.w3c.dom.Document构建XML文档,以便为另一个现有工具创建一些XML。我遇到的问题是该工具似乎以一种奇怪的方式具有XML命名空间。我如何使用Java API来复制它?

<ns1:myroot xmlns:ns1="http://foo.com/ns1/">
  <ns2:bar xmlns:ns2="http://foo.com/xml/bar/">
    <ns2:bar_thing>abc</ns2:bar_thing>
  </ns2:bar>
  <ns3:data xmlns:ns3="http://foo.com/xml/special-ns">
    <!--These are not namespaced for some reason. If I use the ns3 prefix, or
      use a default xmls="...", the tool fails to load the document, saying the
      elements have invalid values.
      -->
      <a>Element without namespace</a>
      <b>
        <bi>1</bi>
        <bii>2</bii>
      </b>
  </ns3:data>
</ns1:myroot>

我可以使用createElementNSsetAttributeNS轻松构建大部分文档。但是,我无法使ns3:data内容正确无误。

尝试使用非命名空间createElement仍然在我的xmlns="http://foo.com/xml/special-ns">a元素上留下b,就像使用带有空命名空间的createElementNS一样,显然非空命名空间将它们放在命名空间中。

http://foo.com/xml/special-ns的架构有如下所示的一堆声明,不确定tns的内容是什么,但其他方面似乎并不特别(尽管我并不是100%确定该工具实际上使用XSD做任何事情,我无法访问源代码。

<xs:schema version="1.0" targetNamespace="http://foo.com/xml/special-ns">
  <!--Bunch of xs:element such as this-->
  <xs:element name="data" type="tns:data" />

  <!--types declared after-->
  <xs:complexType name="data">
    <xs:sequence>
      <xs:element name="a" type="tns:aDataObj" minOccurs="0"/>
      <xs:element name="b" type="tns:bDataObj" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>

  <xs:simpleType name="aDataObj">
    <xs:restriction base="xs:string">
      <xs:pattern value="[a-zA-Z0-9 ]+" />
    </xs:restriction>
  </xs:simpleType>

  <xs:complexType name="bDataObj">
    <xs:sequence>
      <xs:element name="bi" type="xs:string"/>
      <xs:element name="bii" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

0 个答案:

没有答案
相关问题