gpt4 book ai didi

java - 如何使用 xpath 和 Java 删除简单元素中的整个节点

转载 作者:行者123 更新时间:2023-12-02 03:42:02 27 4
gpt4 key购买 nike

我有一个像这样的 xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<User SOURCE_NAME="PublicAssetFeed" xmlns="http://abc.e.wat.com/xml">
<Employee>
<FIELD NAME="Name" TYPE="char">Rahul</FIELD>
<FIELD NAME="Branch" TYPE="char"></FIELD>
<FIELD NAME="Unique ID" TYPE="char">12345</FIELD>
</Employee> `

我想删除其中 NAME="Branch" 的整行。所以我的最终 XML 应该如下所示

`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<User SOURCE_NAME="PublicAssetFeed" xmlns="http://abc.e.wat.com/xml">
<Employee>
<FIELD NAME="Name" TYPE="char">Rahul</FIELD>
<FIELD NAME="Unique ID" TYPE="char">12345</FIELD>
</Employee>
</User>`

我需要使用 Java 来完成此操作。上面的 XML 存储为字符串。因此,我需要将其转换为 XML,删除特定行,然后转换回字符串。我尝试使用 XPath,但只能使用下面的 Java 代码找到“FIELD”主节点。如何删除 NAME="Branch"的整行

package com.javamultiplex;
import java.io.IOException;
import java.io.StringReader;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
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.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

public class test {

public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException{
String abc="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><User SOURCE_NAME=\"PublicAssetFeed\" xmlns=\"http://abc.e.wat.com/xml\"><Employee><FIELD NAME=\"Name\" TYPE=\"char\">Rahul</FIELD><FIELD NAME=\"Unique ID\" TYPE=\"char\">12345</FIELD><FIELD NAME=\"Branch\" TYPE=\"char\"></FIELD></Employee></User>"
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
XPath xPath = XPathFactory.newInstance().newXPath();
InputSource sourceMasterTitle = new InputSource(new StringReader(abc.toString()));
String expression = "//FIELD[@NAME='Branch']";;
Node value = (Node) xPath.evaluate(expression, sourceMasterTitle ,XPathConstants.NODE);
System.out.println("Main node is "+value.getNodeName());
}
}

最佳答案

XML 文件是基于树结构的灵活且智能的结构。最好将代码设计为遍历节点并删除要删除的节点。

可以更改缩进,可以更改 XML 文件的结构。如果您采用“删除一行”之类的方法,您的代码可能会过时。

除此之外,您还必须将字符串转换为 Document 并遍历其节点。

package stackoverflow;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathExpressionException;

import org.xml.sax.InputSource;

public class XMLTester {

public static void main(String[] args)
throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<User xmlns=\"http://abc.e.wat.com/xml\" SOURCE_NAME=\"PublicAssetFeed\">" + " <Employee>"
+ " <FIELD NAME=\"Name\" TYPE=\"char\">Rahul</FIELD>"
+ " <FIELD NAME=\"Branch\" TYPE=\"char\" />"
+ " <FIELD NAME=\"Unique ID\" TYPE=\"char\">12345</FIELD>" + " </Employee>" + "</User>";

Document doc = readStringAsDocument(xmlStr);

try {
printDocument(doc, System.out);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Node willBeDeleted = null;

NodeList fieldNodes = doc.getElementsByTagName("FIELD");

if (fieldNodes.getLength() > 0) {
for (int i = 0; i < fieldNodes.getLength(); i++) {
Node node = fieldNodes.item(i);
NamedNodeMap attributes = node.getAttributes();

for (int j = 0; j < attributes.getLength(); j++) {
Node att = attributes.item(j);

if (att.getNodeName().equals("NAME") && att.getNodeValue().equals("Branch")) {
willBeDeleted = node;
}
}
}
}

willBeDeleted.getParentNode().removeChild(willBeDeleted);

try {
printDocument(doc, System.out);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private static Document readStringAsDocument(String xmlString)
throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = null;

db = dbf.newDocumentBuilder();

Document doc = db.parse(new InputSource(new StringReader(xmlString)));
return doc;
}

// https://stackoverflow.com/a/2325407/2384806
public static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}
}

关于java - 如何使用 xpath 和 Java 删除简单元素中的整个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56831230/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com