我的任務是修改包含RSS源的字符串。它有它的元素。我需要修改這些鏈接元素,然後輸出整個事情。我試過使用Documentbuilder,但每次嘗試修改節點時都會刪除所有後代節點。如何修改XML文件的元素然後打印整個東西
任何人都可以提出一個簡單的方法來檢索和修改這些節點,然後打印整個飼料。
public Document XMLParser(String rssFeed){
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
String nodeContents = null;
String newXML = "";
try {
docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new ByteArrayInputStream(rssFeed.getBytes("utf-8"))));
Node node = doc.getFirstChild();
NodeList list = node.getChildNodes();
NodeList nodeList = doc.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node curNode = nodeList.item(i);
if ("link".equals(curNode.getNodeName()) || "channel".equals(curNode.getNodeName())) {
nodeContents = curNode.getTextContent();
nodeContents = "new contents";
curNode.setTextContent(nodeContents);
}
}
return doc;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
RSS樣本:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>title for the channel</title>
<link><![CDATA[www.whatever.com]]></link>
<description><![CDATA[description of the channel.]]></description>
<item>
<title><![CDATA[title of the link]]></title>
<description><![CDATA[description of the link]]></description>
<link><![CDATA[www.whatever.com]]></link>
<enclosure url="thepictureURL" length="21830" type="image/png" />
<pubDate>Thu, 01 Jan 2000 00:00:00 EDT</pubDate>
</item>
</channel>
</rss>
向我們展示您的代碼(刪除後代節點的代碼) – rzymek
好的,我添加了有問題的代碼。 – popbottlepirate
還包括您的RSS數據樣本。 – rzymek