Java 将XML解析为自定义格式

Java 将XML解析为自定义格式,java,xml,xml-parsing,xmlstreamreader,Java,Xml,Xml Parsing,Xmlstreamreader,我有以下意见: <soapenv:Envelope xmlns:soapenv="http://schemas.xmlrest.org/soap/envelope/" xmlns:ws="http://somepage.net/sk/caf/ws"> <soapenv:Header> <ws:messageIdHeader> <ws:messageId>1234545</ws:messageId>

我有以下意见:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlrest.org/soap/envelope/" xmlns:ws="http://somepage.net/sk/caf/ws">
   <soapenv:Header>
      <ws:messageIdHeader>
         <ws:messageId>1234545</ws:messageId>
      </ws:messageIdHeader>
      <ws:messageIdHeader>
         <ws:messageId>9999999</ws:messageId>
      </ws:messageIdHeader>
   </soapenv:Header>
   <soapenv:Body>
      <ws:getClientRequest>
         <ws:caid>000899</ws:caid>
      </ws:getClientRequest>
   </soapenv:Body>
</soapenv:Envelope>
我尝试了一些DOM操作,但仍然没有得到所需的结果。 问题在于调用方法getNextSiblings.getNodeName()/GetPreviousSiblines.getNodeName()时。他们没有返回标签的名称,只是一些废话。我不知道哪个元素有兄弟元素。Simple说,我需要索引元素,它有兄弟元素,但我不知道怎么做。 你有什么建议吗?:)

这是我使用的代码,但没有要求的结果:

public static void main(String[] args) throws Exception {
        File file = new File("/Some/path/tothis.xml");
        XPath xPath =  XPathFactory.newInstance().newXPath();
        String expression = "//*[not(*)]";

        DocumentBuilderFactory builderFactory =
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(file);
        document.getDocumentElement().normalize();

        NodeList nodeList = (NodeList)
                xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
        for(int i = 0 ; i < nodeList.getLength(); i++) {
            System.out.println("| "+ new Parser2().getNodePath(nodeList.item(i)) +" | " + nodeList.item(i).getTextContent() + " |");
        }
    }

    public String getNodePath(Node node) {
        if(node == null) {
            throw new IllegalArgumentException("Node cannot be null");
        }
        StringBuilder pathBuilder = new StringBuilder(".");
        String [] lastNode = node.getNodeName().split(":");
        pathBuilder.append(lastNode[1]);

        Node currentNode = node;

        if(currentNode.getNodeType() != Node.DOCUMENT_NODE) {
            while (currentNode.getParentNode() != null) {
                currentNode = currentNode.getParentNode();

                if(currentNode.getNodeType() == Node.DOCUMENT_NODE) {
                    break;
                } else if(getIndexOfArrayNode(currentNode) != null) {
                    String [] nodeName = currentNode.getNodeName().split(":");
                    pathBuilder.insert(0, nodeName[1] +  getIndexOfArrayNode(currentNode).toString() +".");
                } else {
                    String [] nodeName = currentNode.getNodeName().split(":");
                    pathBuilder.insert(0, nodeName[1] +"." );
                }
            }
        }

        return pathBuilder.toString();
    }

    private boolean isArrayNode(Node node) {
        if (node.getNextSibling() == null && node.getPreviousSibling() == null) {
            // Node has no siblings
            return false;
        } else {
            // Check if node siblings are of the same name. If so, then we are inside an array.
            return (node.getNextSibling() != null && node.getNextSibling().getNodeName().equalsIgnoreCase(node.getNodeName()))
                    || (node.getPreviousSibling() != null && node.getPreviousSibling().getNodeName().equalsIgnoreCase(node.getNodeName()));
        }
    }

    private Integer getIndexOfArrayNode(Node node) {
        if(isArrayNode(node)) {
            int leftCount = 0;

            Node currentNode = node.getNextSibling();

            while(currentNode != null) {
                leftCount++;
                currentNode = currentNode.getPreviousSibling();
            }
            return leftCount;
        } else {
            return null;
        }
    }
publicstaticvoidmain(字符串[]args)引发异常{
File File=新文件(“/Some/path/tothis.xml”);
XPath=XPathFactory.newInstance().newXPath();
字符串表达式=“/*[非(*)]”;
文档构建器工厂构建器工厂=
DocumentBuilderFactory.newInstance();
DocumentBuilder=builderFactory.newDocumentBuilder();
Document=builder.parse(文件);
document.getDocumentElement().normalize();
NodeList NodeList=(NodeList)
compile(表达式).evaluate(文档,XPathConstants.NODESET);
for(int i=0;i

非常感谢

请发布您的代码。发布,thx,我的意思是,仅使用XMLStreamReader是不可能的,但我需要将每个元素强制转换为节点,但有一个问题:/code我使用的东西不返回元素的索引,它返回每个事件,但只需要路径值,thx大多数人使用XSLT将XML转换为文本。它可以很精细,但Java也可以很精细(正如您所发现的)。如果您喜欢坚持使用Java解决方案,我建议使用DOM而不是XMLStreamReader。这样,您将在内存中拥有整个XML树,并且很容易从父节点获取索引。
public static void main(String[] args) throws Exception {
        File file = new File("/Some/path/tothis.xml");
        XPath xPath =  XPathFactory.newInstance().newXPath();
        String expression = "//*[not(*)]";

        DocumentBuilderFactory builderFactory =
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(file);
        document.getDocumentElement().normalize();

        NodeList nodeList = (NodeList)
                xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
        for(int i = 0 ; i < nodeList.getLength(); i++) {
            System.out.println("| "+ new Parser2().getNodePath(nodeList.item(i)) +" | " + nodeList.item(i).getTextContent() + " |");
        }
    }

    public String getNodePath(Node node) {
        if(node == null) {
            throw new IllegalArgumentException("Node cannot be null");
        }
        StringBuilder pathBuilder = new StringBuilder(".");
        String [] lastNode = node.getNodeName().split(":");
        pathBuilder.append(lastNode[1]);

        Node currentNode = node;

        if(currentNode.getNodeType() != Node.DOCUMENT_NODE) {
            while (currentNode.getParentNode() != null) {
                currentNode = currentNode.getParentNode();

                if(currentNode.getNodeType() == Node.DOCUMENT_NODE) {
                    break;
                } else if(getIndexOfArrayNode(currentNode) != null) {
                    String [] nodeName = currentNode.getNodeName().split(":");
                    pathBuilder.insert(0, nodeName[1] +  getIndexOfArrayNode(currentNode).toString() +".");
                } else {
                    String [] nodeName = currentNode.getNodeName().split(":");
                    pathBuilder.insert(0, nodeName[1] +"." );
                }
            }
        }

        return pathBuilder.toString();
    }

    private boolean isArrayNode(Node node) {
        if (node.getNextSibling() == null && node.getPreviousSibling() == null) {
            // Node has no siblings
            return false;
        } else {
            // Check if node siblings are of the same name. If so, then we are inside an array.
            return (node.getNextSibling() != null && node.getNextSibling().getNodeName().equalsIgnoreCase(node.getNodeName()))
                    || (node.getPreviousSibling() != null && node.getPreviousSibling().getNodeName().equalsIgnoreCase(node.getNodeName()));
        }
    }

    private Integer getIndexOfArrayNode(Node node) {
        if(isArrayNode(node)) {
            int leftCount = 0;

            Node currentNode = node.getNextSibling();

            while(currentNode != null) {
                leftCount++;
                currentNode = currentNode.getPreviousSibling();
            }
            return leftCount;
        } else {
            return null;
        }
    }