开发者

Is there a Java library to validate that an XML snippet is a subset of a larger XML file?

I'm looking for code which can do the following. Given a snippet of XML, say:

<c>Some text</c>

and a complete XML file:

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

check that the snippet is indeed a valid subset of the complete XML file. I've been looking at XMLUnit which looks really good, but it seems to only validate complete files against each other.

For the sample above, a simple string comparison would work, but other features I would like to support might be:

开发者_JAVA技巧

1) Order of child elements not important. E.g.

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

is a valid subset of

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

2) Ignore whitespace, tabs, new lines etc.

3) A nice to have would be XMLUnit's skeleton feature where node names and structure are checked, but not content values. E.g. <c>Some text</c> would be valid when compared against <c>Other text</c>.


I don't think there's such a library but you could solve it in the following way (if your xml fragment starts with an element). I assume you are familiar with 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜