Is there a Java library to verify that an XML fragment is a subset of a larger XML file?

I am looking for code that can do the following. Given an XML fragment, let's say:

<c>Some text</c>

and the full XML file:

<a>
   <b>
      <c>Some text</c>
   </b>
</a>

verify that the fragment is indeed a valid subset of the complete XML file. I looked at XMLUnit , which looks really good, but seems to only check the complete files against each other.

For the example above, a simple string comparison will be performed, but other functions that I would like to support might be:

1) The order of the baby items is not important. For instance.

<b>
   <c>Some text</c>
   <d>Other text</d>
</b>

is a valid subset

<a>
   <b>
      <d>Other text</d>
      <c>Some text</c>
   </b>
</a>

2) , , ..
3) XMLUnit, node, . . <c>Some text</c> <c>Other text</c>.

+3
1

, , ( xml- ). , XMLUnit.

public boolean isSubset(Document document, Element element) {
    NodeList list = document.getElementsByTagName(element.getNodeName());
    for (int i = 0; i < list.getLength(); i++) {
        Element el = (Element) list.item(i);
        Document clone = toNewDocument(el);
        //compare element with clone with XMLUnit
        //...
        if (equal) {
            return true;
        }
    }
    return false;
}

private Document toNewDocument(Element el) {
    // createing a new DOM-document...
    Document document = documentBuilder.newDocument();
    Node node = document.importNode(el, true);
    document.getDocumentElement().appendChild(node);
    return document;
}
+1

Source: https://habr.com/ru/post/1776871/


All Articles