从java中的XML文件中删除元素 [英] remove elements from XML file in java
问题描述
我已经从excel数据库生成了一个xml文件,它自动包含一个名为 offset
的元素。为了使我的新文件符合我的需要,我想使用java删除这个元素。
这里是xml内容:
I have generated an xml file from an excel data base and it contains automatically an element called "offset
". To make my new file match my needs, I want to remove this element using java.
here is the xml content:
<Root><models><id>2</id><modelName>Baseline</modelName><domain_id>2</domain_id><description> desctiption </description><years><Y2013>value1</Y2013><Y2014>value2</Y2014><Y2015>value3</Y2015><Y2016>value4</Y2016><Y2017>value5</Y2017></years><offset/></models></Root>
我创建了一个代码(使用缓冲读取器)并将内容写入新文件中使用条件if:
I made a code that reads(with a buffered reader) and writes the content in a new file and used the condition if:
while (fileContent !=null){
fileContent=xmlReader.readLine();
if (!(fileContent.equals("<offset/>"))){
System.out.println("here is the line:"+ fileContent);
XMLFile+=fileContent;
}
}
但确实如此不工作
推荐答案
我个人建议使用适当的XML解析器,如Java DOM 检查和删除节点,而不是将XML作为原始XML处理 String
s(哎呀)。尝试这样的方法来删除你的'偏移'节点。
I would personally recommend using a proper XML parser like Java DOM to check and delete your nodes, rather than dealing with your XML as raw String
s (yuck). Try something like this to remove your 'offset' node.
File xmlFile = new File("your_xml.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
NodeList nList = doc.getElementsByTagName("offset");
for (int i = 0; i < nList.getLength(); i++) {
Node node = nList.item(i);
node.getParentNode().removeChild(node);
}
上面的代码删除了xml文件中的所有偏移节点。
The above code removes any 'offset' nodes in an xml file.
如果资源/速度考虑是一个问题(例如当your_xml.xml很大时),那么最好使用 SAX ,它更快(代码密集程度更高)并且不会将XML存储在内存中。
If resources/speed considerations are an issue (like when your_xml.xml is huge), you would be better off using SAX, which is faster (a little more code intensive) and doesn't store the XML in memory.
一旦你的文件
被编辑了,你可能想要将其转换为字符串以解析为您选择的 OutputStream
。
Once your Document
has been edited you'll probably want to convert it to a String to parse to your OutputStream
of choice.
希望这会有所帮助。
这篇关于从java中的XML文件中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!