我尝试使用Java编辑XML文件,我需要编辑内容和内容。用我想要的内容替换它们
(我想将Deutsh中的一些节点替换为法语
[用于示例<fr>DE1</fr>
到<fr>FR1</fr>
])
我试图使用:
node.setTextContent(Value);
node.setNodeValue(Value);
但它根本不起作用 是否还有其他功能可以在下面编辑这些节点?
以下是代码:
for (int i = memory; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if ((langu.equals(node.getNodeName()))) //langu = "fr"
{
test = node.getTextContent();
if(isCorrect()){}
else if ((manualTr.clickCount >= 0)
){
trash = test;
node.setTextcontent(Value);
// node.setNodeValue("Test");
memory += manualTr.clickCount;
manualTr.clickCount -= 1;
}
}
}
这是XML代码:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<titles>
<tome>
<de>DE1</de>
<fr>DE1</fr>
<en>EN1</en>
</tome>
<valhalla>
<de>DE2</de>
<fr>DE2</fr>
<en>EN2</en>
</valhalla>
<vikings>
<de>DE3</de>
<fr>DE3</fr>
<en>EN3</en>
</vikings>
</titles>
答案 0 :(得分:0)
试试这个..我正在使用setTextContent()来更新节点值。
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* @author JayaPrasad
*
*/
public class ParseXml {
public static void main(String[] args) {
System.out.println("Started XML modification");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document xmlDoc;
xmlDoc = docBuilder.parse(new File("sample.xml"));
NodeList nodes = xmlDoc.getElementsByTagName("fr");
for (int i = 0, length = nodes.getLength(); i < length; i ++) {
((Element)nodes.item(i)).setTextContent("Modified");
}
xmlDoc.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource domSource = new DOMSource(xmlDoc);
StreamResult result = new StreamResult(new File("sample.xml"));
transformer.transform(domSource, result);
System.out.println("Modification Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}