在XML标签之间提取内容

时间:2018-10-09 11:38:09

标签: java xml parsing

我有这个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>相似,但我还是很简单。

我想做的是提取<Entity></Entity>标签之间的所有内容。 我已经做了很多研究,但是我发现最接近的是从一个标签中提取内容。

结果就是这个

<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>标签。

非常感谢您。

编辑

`公共类ReadXMLFile {     私有的最终静态String文件路径=“ 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);
}

} `

它不会显示任何错误,因为它似乎无能为力。

1 个答案:

答案 0 :(得分:1)

您可以采用旧的好方法。

  1. 将XML读取为DOM
  2. 使用XPath提取适当的部分
  3. 打印出来...或做任何您想做的事

代码:

@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);
}

How to read XML using XPath in Java

中可以找到某种概括的形式。