dom—从java程序向xsd添加根元素

jgwigjjp  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(331)

我看到过一些文章,其中我们可以向xml添加一个根元素,但我想在传入的xsd周围特别添加一个根复杂元素。我在这里看到两种情况,其中现有的xsd根元素是命名类型或匿名类型:
因此,如果具有命名根元素的xsd:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
   targetNamespace="http://a.b/c/d" elementFormDefault="qualified"> 
            <xs:element name="oldRoot" type="oldRoot"/>

应转换为:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
   targetNamespace="http://a.b/c/d" elementFormDefault="qualified"> 
 <xs:element name="newRoot">
  <xs:complexType>
   <xs:sequence>  
    <xs:element name="oldRoot" type="oldRoot"/>
   </xs:sequence>
  </xs:complexType>
</xs:element>

以及匿名类型的xsd:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://a.b/c/d" elementFormDefault="qualified">
     <xs:element name="oldRoot">
       <xs:complexType>           
         <xs:sequence>
            <xs:element name="oldChild1">
               <xs:complexType>
                 <xs:sequence>
                    <xs:element name="someElement" type="xs:string"/> 
                 </xs:sequence>        
               </xs:complexType>
            </xs:element>
       </xs:sequence>
     </xs:complexType>
   </xs:element>

应该转变为

<xs:element name="newRoot">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="oldRoot"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>
<xs:complexType name="oldRoot">
  <xs:sequence>
    <xs:element name="oldChild1">
      <xs:complexType>
        <xs:sequence>
            <xs:element name="someElement" type="xs:string"/>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
  </xs:sequence>
</xs:complexType>

我在玩dom解析器来帮助我进行这些编辑,但是dom解析器可以用于以上两种情况吗?
那么,我可以构造新的根元素,然后将旧的根元素嵌入其中吗?这就是我能解决这个问题的方法还是有别的办法?
代码:

is = new FileInputStream("/home/xyz/testing.xsd");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document oldDoc = builder.parse(is);

Node oldRoot = oldDoc.getDocumentElement();

Document newDoc = builder.newDocument();

Element newComplexType = newDoc
.createElement("xs:complexType");
Element newSequence = newDoc.createElement("xs:sequence");
Element newElement = newDoc.createElement("xs:element");
newComplexType.setAttribute("name", "newRoot"); 

newDoc.appendChild(newComplexType);

newComplexType.appendChild(newDoc.importNode(oldRoot, true));
wfypjpf4

wfypjpf41#

dom代表文档对象模型。使用dom文档时,您使用的对象包含文档的模型(结构),您可以附加元素、删除元素等,并且模型(dom对象/文档的结构)将发生更改,但这不会更改任何文件内容,除非您专门将dom写入文件。
这意味着您不需要创建两个文档。您应该只从文件中创建一个dom文档,然后修改dom(移动和创建节点)并将dom内容写入文件。

final String XS_URI = "http://www.w3.org/2001/XMLSchema";
FileInputStream is = new FileInputStream("xsd2.xsd");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); 
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(is); // Our DOM document
XPath xpath = XPathFactory.newInstance().newXPath();

// Search required xs:element (old element)
XPathExpression firstElementExpr = xpath.compile("/*/*[local-name()='element'][1]");
Element element = (Element) firstElementExpr.evaluate(doc, XPathConstants.NODE);

// Create new elements, add them to Document Object Model
Element newElement = doc.createElementNS(XS_URI, "element");
Element newComplexType = doc.createElementNS(XS_URI, "complexType");
Element newSequence = doc.createElementNS(XS_URI, "sequence");
doc.getDocumentElement().appendChild(newElement); // new xs:element inside xs:schema
newElement.appendChild(newComplexType); // new xs:complexType inside new xs:element
newComplexType.appendChild(newSequence); // new xs:sequence inside new xs:complexType
newElement.setAttribute("name", "newRoot"); // Add name attribute
// Note that the order of these operations can be changed, the resulting DOM should be the same.

newSequence.appendChild(element); // The old element is moved inside the new xs:sequence
if (element.hasAttribute("type")) {
    // Everything is done (the old element have been moved inside the new sequence)
} else {
    NodeList childNodes = element.getChildNodes(); // Nodes inside old element. This also contains comments (<!-- -->), text nodes, etc
    for (int i=0; i<childNodes.getLength(); i++) {
        /*
         * We iterate nodes till we found xs:complexType
         * Then we move xs:comlpexType inside xs:schema and add the required name attribute
         */
        if ("complexType".equals(childNodes.item(i).getLocalName())) {
            Element complexType = (Element) childNodes.item(i);
            complexType.setAttribute("name", "oldRoot"); // Maybe in your specific case, attribute value should be element.getAttribute("name")??
            doc.getDocumentElement().appendChild(complexType);
        }
    }
}
saveDocument(doc, "newXSD.xsd");

最后,您可以将dom文档写入一个文件,或者像您在许多stackoverflow问题中看到的那样作为一个字符串。

相关问题