在XML标签之间提取内容 [英] Extract content between XML tags
问题描述
我有这个XML文件:
<ApiHeader>
<OperationName>findEntitiesResponse</OperationName>
</ApiHeader>
<ResponseHeader>
<CompletedSuccessfully>true</CompletedSuccessfully>
</ResponseHeader>
<Page>
<StartAtRow>0</StartAtRow>
<MaxRows>999999</MaxRows>
<TotalRowCount>44</TotalRowCount>
</Page>
<Entity>
<Carrier>xd
<Id>11460</Id>
<CarrierCode>11460</CarrierCode>
<CarrierDescription>11460 LOGIS COUTTER</CarrierDescription>
<LanguageCode>en</LanguageCode>
<LanguageCodeDescr>Inglés</LanguageCodeDescr>
<CarrierTypeCode>GENERAL</CarrierTypeCode>
<CarrierTypeCodeDescr>GENERAL</CarrierTypeCodeDescr>
<SCACCode>Default</SCACCode>
</Memo>
</Carrier>
</Entity>
<Entity>
有许多<Entitiy>CONTENT</Entity>
类似于示例中的<Entitiy>CONTENT</Entity>
,但我保持简单.
There are a lot of <Entitiy>CONTENT</Entity>
like the one on the example, but I kept it simple.
我想做的是提取<Entity></Entity>
标记之间的所有内容.
我已经做了很多研究,但是我发现最接近的是从一个标签中提取内容.
What I'm trying to do is extract everything between the <Entity></Entity>
tags.
I've done a lot of research but the closest thing I've found is extracting content from just one tag.
结果就是这个
<Entity>
<Carrier>xd
<Id>11460</Id>
<CarrierCode>11460</CarrierCode>
<CarrierDescription>11460 LOGIS COUTTER</CarrierDescription>
<LanguageCode>en</LanguageCode>
<LanguageCodeDescr>Inglés</LanguageCodeDescr>
<CarrierTypeCode>GENERAL</CarrierTypeCode>
<CarrierTypeCodeDescr>GENERAL</CarrierTypeCodeDescr>
<SCACCode>Default</SCACCode>
</Memo>
</Carrier>
</Entity>
请记住,可能有一个或多个<Entity></Entity>
标签.
Remeber that there could be one or more <Entity></Entity>
tags.
非常感谢您.
编辑
`公共类ReadXMLFile { 私有的最终静态String文件路径="C:\ Users \ AGOJSO \ Desktop \ jordi \ test.xml";
`public class ReadXMLFile { private final static String filepath ="C:\Users\AGOJSO\Desktop\jordi\test.xml";
public static void main(String[] args) {
printXml();
}
public static void printXml() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try (InputStream in = new FileInputStream(filepath)) {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(in);
NodeList list = filterNodesByXPath(doc, "//root/Entity");
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
printNode(node);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static NodeList filterNodesByXPath(Document doc, String xpathExpr) {
try {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression expr = xpath.compile(xpathExpr);
Object eval = expr.evaluate(doc, XPathConstants.NODESET);
return (NodeList) eval;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void printNode(Node node) throws TransformerFactoryConfigurationError, TransformerException {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(node);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
}
} `
它不会显示任何错误,因为它似乎无能为力.
It doesnt print any errors, as it it seems to be doing nothing.
推荐答案
您可以使用旧的好方法.
You could do it the old good way.
- 将XML读取为DOM
- 使用XPath提取适当的部分
- 打印出来...或做任何您想做的事
代码:
@Test
public void printXml() {
String yourSampleFile = "52720162.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(yourSampleFile)) {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(in);
NodeList list = filterNodesByXPath(doc, "//root/Entity");
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
printNode(node);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private NodeList filterNodesByXPath(Document doc, String xpathExpr) {
try {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression expr = xpath.compile(xpathExpr);
Object eval = expr.evaluate(doc, XPathConstants.NODESET);
return (NodeList) eval;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void printNode(Node node) throws TransformerFactoryConfigurationError, TransformerException {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(node);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
}
可以在以下位置找到某种概括的形式:如何在Java中使用XPath读取XML
A somewhat generalized form can be found at: How to read XML using XPath in Java
这篇关于在XML标签之间提取内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!