gpt4 book ai didi

Java XML - 删除节点后 - 空白行仍然存在 - 如何删除?

转载 作者:数据小太阳 更新时间:2023-10-29 02:25:46 33 4
gpt4 key购买 nike

我正在使用 javax.xml 并在删除一些节点后:

docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
document = docBuilder.parse(new File("file_name"));
NodeList tagList = document.getElementsByTagName("tag_name");
tagList.item(0).getParentNode().removeChild(waysList.item(0));

我有一个空行,而不是删除的标签。

如何避免这种情况或删除空行?

XML 文件是:

<root>
<tag_name>text</tag_name>
<tag_name>text</tag_name>
<tag_name>text</tag_name>
</root>

编辑:如果我在 removeChild 之前或之后添加 tagList.item(0).getParentNode().setTextContent(""); 我会得到 NullPointerException。

谢谢,

最佳答案

元素前缩进,元素后回车是文本节点。如果您删除一个元素并且在它之前或之后有一个文本节点,您将看到它作为空白行。

 public static void main(String[] args){
File file=new File(XmlProcessing.class.getResource("InputXml.txt").getFile());
// create a new DocumentBuilderFactory
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(file);
System.out.println("Before removing the Node:-");
printDocument(document, System.out);
NodeList tagList = document.getElementsByTagName("tag_name");
Element elemToBeRemoved = (Element)tagList.item( 0 );
Node prevElem = elemToBeRemoved.getPreviousSibling();
if (prevElem != null &&
prevElem .getNodeType() == Node.TEXT_NODE &&
prevElem .getNodeValue().trim().length() == 0) {
elemToBeRemoved.getParentNode().removeChild(prevElem );
}
elemToBeRemoved.getParentNode().removeChild( elemToBeRemoved );
System.out.println("\nAfter removing the node:-");
printDocument(document, System.out);


}catch(Exception excep){
excep.printStackTrace();
}

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


/** Output:-
Before removing the Node:-
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<tag_name>text</tag_name>
<tag_name>text</tag_name>
<tag_name>text</tag_name>
</root>

After removing the node:-
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<tag_name>text</tag_name>
<tag_name>text</tag_name>
</root>

*/

关于Java XML - 删除节点后 - 空白行仍然存在 - 如何删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41533638/

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