在下面的XML中,我需要搜索标签 attrGroupMany name =“allergenRelatedInformation”和删除除了第一个之外的所有子节点()。
不确定XSLT / Java DOM是否是实现此功能的最佳方式。请帮助。
XPathExpression delExpr = xpath.compile("//flexTM/attrGroupMany[starts-with(@name,'allergenRelatedInformation')]/row");
Object obj = expr.evaluate(doc, XPathConstants.NODESET);
NodeList row = (NodeList) obj;
for(int i = 1; i < row.getLength(); i++)
{
Node attr = row.item(i);
Element e = (Element) attr;
System.out.println(row.item(i).getParentNode().getNodeName());
row.item(1).getParentNode().removeChild(e);
doc.normalize();
i-- }
<attrGroupMany name="manufacturer">
<row>
<attr name="gln">123456</attr>
<attr name="name">ABC Inc</attr>
</row>
</attrGroupMany>
<attrGroupMany name="allergenRelatedInformation">
<row>
<attr name="allergenSpecificationAgency">FDA</attr>
<attr name="allergenSpecificationName">BIG 8</attr>
<attrGroupMany name="allergen">
<row>
<attr name="allergenTypeCode">AC</attr>
<attr name="levelOfContainmentCode">FREE_FROM</attr>
</row>
</attrGroupMany>
</row>
<row>
<attr name="allergenSpecificationAgency">FDA</attr>
<attr name="allergenSpecificationName">BIG 8</attr>
<attrGroupMany name="allergen">
<row>
<attr name="allergenTypeCode">AE</attr>
<attr name="levelOfContainmentCode">FREE_FROM</attr>
</row>
</attrGroupMany>
</row>
<row>
<attr name="allergenSpecificationAgency">FDA</attr>
<attr name="allergenSpecificationName">BIG 8</attr>
<attrGroupMany name="allergen">
<row>
<attr name="allergenTypeCode">AF</attr>
<attr name="levelOfContainmentCode">FREE_FROM</attr>
</row>
</attrGroupMany>
</row>
<row>
<attr name="allergenSpecificationAgency">FDA</attr>
<attr name="allergenSpecificationName">BIG 8</attr>
<attrGroupMany name="allergen">
<row>
<attr name="allergenTypeCode">AM</attr>
<attr name="levelOfContainmentCode">FREE_FROM</attr>
</row>
</attrGroupMany>
</row>
</attrGroupMany>
答案 0 :(得分:0)
如果您希望xml中的输出不需要进行进一步处理,那么XSLT是最佳选择。否则,JDOM是一个解析您正在寻找的节点的选项,并在稍后的相同Java代码中执行所需的业务逻辑。