java - 如何修改 XML 文件的元素然后打印整个内容

标签 java xml rss

我的任务是修改包含 RSS 提要的字符串。它有元素在里面。我需要修改这些链接元素,然后输出整个内容。我尝试过使用 Documentbuilder,但每次尝试修改节点时,它都会删除所有后代节点。

任何人都可以建议一种简单的方法来检索和修改这些节点,然后打印整个提要。

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>

最佳答案

留意 setTextContent(text) 。如果您在具有子节点的节点上调用它,这些子节点将被替换为 text .

如果 RSS 不太大,您可以将其加载到内存中 - 将其解析为 DOM。修改<link>的内容节点。然后将 DOM 序列化回字符串:

public static String processLinks(String rssFeed) throws Exception {
  DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = docFactory.newDocumentBuilder();
  Document doc = builder.parse(new InputSource(new StringReader(rssFeed)));

  NodeList nodeList = doc.getElementsByTagName("link");
  for (int i = 0; i < nodeList.getLength(); i++) {
    Node link = nodeList.item(i);
    String value = link.getTextContent();
    //Do the processing. For example:
    if(!value.startsWith("http://")) {
      link.setTextContent("http://"+value);
    }
  }
  return toString(doc);
}

private static String toString(Document doc) throws Exception {
  TransformerFactory tf = TransformerFactory.newInstance();
  Transformer transformer = tf.newTransformer();
  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  StringWriter writer = new StringWriter();
  transformer.transform(new DOMSource(doc), new StreamResult(writer));
  return writer.toString();
}

关于java - 如何修改 XML 文件的元素然后打印整个内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20554432/

相关文章:

android - 外部链接无法打开 phonegap cordova android

xml - RSS 中的缩略图有一些标准的 xml 标签吗?

javascript - 如何将java变量传递到包含javascript的不同jsp页面?

java - Gradle 日志记录输出级别

java - 使用 SWIG 将 Java Map<String, String> 传递给 C++ 方法

c# - 使用 C# Linq to XML 创建 XML 输出后包含重复值

sql-server - SQL Server 2008 - 将 XML 声明添加到 XML 输出

c# - 阅读 RSS 时出错

ruby-on-rails - 如何在 Rails 3 中创建原子提要?

java - UDP 数据包 NPE - Java