我有以下XML字符串。使用JDOM Java拆分XML
<Engineers>
<Engineer>
<Name>JOHN</Name>
<Position>STL</Position>
<Team>SS</Team>
</Engineer>
<Engineer>
<Name>UDAY</Name>
<Position>TL</Position>
<Team>SG</Team>
</Engineer>
<Engineer>
<Name>INDRA</Name>
<Position>Director</Position>
<Team>PP</Team>
</Engineer>
</Engineers>
我需要在XPath是給出工程師/ ENGINNER這個XML分割成較小的XML字符串。
較小的XML字符串如下
<Engineer>
<Name>INDRA</Name>
<Position>Director</Position>
<Team>PP</Team>
</Engineer>
<Engineer>
<Name>JOHN</Name>
<Position>STL</Position>
<Team>SS</Team>
</Engineer>
我已經實現了使用撒克遜XPath和JDOM以下。
import net.sf.saxon.Configuration;
import net.sf.saxon.lib.NamespaceConstant;
import net.sf.saxon.om.DocumentInfo;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.XPathCompiler;
import net.sf.saxon.s9api.XPathSelector;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.xpath.XPathFactoryImpl;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.junit.Test;
import org.xml.sax.InputSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.StringReader;
import java.util.Iterator;
import java.util.List;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathFactoryConfigurationException;
public void testXML() throws XPathFactoryConfigurationException, XPathExpressionException, Exception {
System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_JDOM,
"net.sf.saxon.xpath.XPathFactoryImpl");
XPathFactory xPathFactory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_JDOM);
XPath xPath = xPathFactory.newXPath();
InputSource inputSource = new InputSource(new File(filename).toURI().toString());
SAXSource saxSource = new SAXSource(inputSource);
Configuration config = ((XPathFactoryImpl) xPathFactory).getConfiguration();
DocumentInfo document = config.buildDocument(saxSource);
XPathExpression xPathExpression = xPath.compile("//Engineers/Engineer");
List matches = (List) xPathExpression.evaluate(document, XPathConstants.NODESET);
if (matches != null) {
for (Iterator iter = matches.iterator(); iter.hasNext();) {
NodeInfo node = (NodeInfo) iter.next();
System.out.println(node.getDisplayName() + " - " + node.getStringValue());
}
}
}
它給出了以下結果。
Engineer -
JOHN
STL
SS
Engineer -
UDAY
TL
SG
Engineer -
INDRA
Director
PP
如何更改代碼,使我得到我想要的輸出?還是有辦法讓名字的子節點屬性(姓名,職務,隊)的內部工程師