6

我需要使用 java xpath 通过 id 将 xml 元素作为字符串返回。

给...

<svg>
    <g id="Background">
    </g>
    <g id="Outline">
        <polygon fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"     stroke-miterlimit="10" points=" 119.813,57.875 119.188,57.87" />
    </g>
    <g id="Base_Colour" transform="matrix(0.25 0 0 0.25 0 0)">
        <path fill="#ADB1AF" d="M112.25,208l-8,20.25l-0.5-1.75l0.75-0.5v-1.5l0.75-0.5v-1.5L106,222v-1.5l0.75-0.5v-1.5l0.75-0.5v-1.5"/>
        <path fill="#625595" d="M112.25,208l5.25-14.5l30-30.25l2.25-1.5l41.5-20.5l49.75-9.5h4.25l49,3l48.75"/>
    </g>
</svg>

返回的值必须是...

<g id="Outline">
    <polygon fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"     stroke-miterlimit="10" points=" 119.813,57.875 119.188,57.87" />
</g> 

我已经广泛搜索,但我尝试过的任何东西都无法返回整个元素。需要 Xpath,因为我想通过 id 查询任何级别的 g 标签。

4

5 回答 5

10

我找到的解决方案是使用 xpath 获取 org.w3c.dom.Node(DOM 也可以)。然后,我从节点创建了一个 javax.xml.transform.dom.DOMSource,并使用 javax.xml.transform.TransformerFactory 将其转换为字符串。

Node node = // the node you want to serialize
xmlOutput = new StreamResult(new StringWriter());
transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node), xmlOutput);
String nodeAsAString = xmlOutput.getWriter().toString();

这很容易被分解为一个类以供重用。不幸的是,Java 中没有 .OuterXml 属性,而 .NET 中没有。现在所有的.NETer 都可以傻笑了。

于 2012-12-19T22:18:20.797 回答
1

xpath 永远不会返回包含 XML 语法的字符串。

于 2012-12-19T01:27:24.767 回答
0

有时您必须在没有 Java 中的 xml 文档的情况下执行此操作;我发现下面的代码非常使用完整

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

String responseMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><YourMessage><MyTag>MyTagValue</MyTag></YourMessage>";
String expressionToExract = "/YourMessage/MyTag";
String xmlNodeWithData = xpathTester.getXmlNode(responseMsg, expressionToExract);
//above xmlNodeWithData will have this value '<MyTag>MyTagValue</MyTag>'

private String getXmlNode(String resultMsg, String expression)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    String xmlNodeWithData="";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = null;
    StringReader sr = null;
    sr = new StringReader(resultMsg);
    is = new InputSource(sr);

    Document doc = builder.parse(is);
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(expression);

    Node node = (Node)expr.evaluate(doc, XPathConstants.NODE);      
    xmlNodeWithData += "<" + node.getNodeName() + ">";
    NodeList nodeList = node.getChildNodes();

    for (int nodeIndex=0; nodeIndex < nodeList.getLength(); nodeIndex++) {
        Node nodeChild = nodeList.item(nodeIndex);          
        if (nodeChild.getNodeName().contains("#text")) {
            xmlNodeWithData += nodeChild.getTextContent();
            continue;
        }
        xmlNodeWithData += "<" + nodeChild.getNodeName() + ">";         
        xmlNodeWithData += nodeChild.getTextContent();
        xmlNodeWithData += "</" + nodeChild.getNodeName() + ">";
    }
    xmlNodeWithData += "</" + node.getNodeName() + ">";
    if (sr != null) {
        sr.close();
    }
    return xmlNodeWithData;
}
于 2019-02-26T22:02:17.460 回答
0

我用这段代码解决了我的问题:

public static String getOuterXml(Node node)
    throws TransformerConfigurationException, TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty("omit-xml-declaration", "yes");

    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(node), new StreamResult(writer));
    return writer.toString();         
}

致谢:chick.Net

于 2017-06-14T19:03:01.433 回答
-1

我不了解 Java,但在 .NET 世界中,人们会使用

doc.DocumentElement.SelectSingleNode("/*/g[@id='Outline']").OuterXml
于 2012-12-19T05:38:22.070 回答