作者:平凡小几 | 来源:互联网 | 2023-09-12 15:24
我有以下输入内容:
1234545
9999999
000899
在这种情况下,必须遵循以下输出:
| Envelope.Header.messageIdHeader.0.messageId | 1234545 |
| Envelope.Header.messageIdHeader.1.messageId | 9999999 |
| Envelope.Body.getclientRequest.caid | 0008997 |
我已经尝试使用DOM进行了一些操作,但仍然没有得到所需的结果。
问题是何时调用方法getNextSiblings.getnodename()/ getPreviousSiblings.getnodename()方法。他们没有返回标签的名称,而是一些废话。而且我不知道哪个元素具有兄弟姐妹。简单地说,我需要索引具有同级元素的元素,但是我不知道该怎么做。
你能给我一些建议吗? :)
这是我使用的代码,但没有必要的结果:
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 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;
}
}
非常感谢