1

它在 XML 中看起来像这样。我想得到他的 Image src 值...

<description><![CDATA[<div class="images"><img src="http://www.voicetv.co.th/cache/images/8a1a6f2aeb7b0e9c1d6bb3eae314165f.jpg" /></div>]]></description>

我正在做的是

if ((theElement.getElementsByTagName("description")).getLength() > 0) {

            allChildern = theElement.getElementsByTagName("description").item(0).getChildNodes();

            for (int index = 0; index < allChildern.getLength(); index++) {
                description += allChildern.item(index).getNodeValue();

                NodeList chNodes = allChildern.item(index).getChildNodes();
                for (int i = 0; i < chNodes.getLength(); i++) {

                    String name = chNodes.item(i).getNodeName();
                    if(name.equals("div")) {
                        String clas = allChildern.item(index).getAttributes().getNamedItem("class").getNodeValue();
                        if(clas.equals("images")){
                            String nName = allChildern.item(index).getChildNodes().item(0).getNodeName();
                            if(nName.equals("img")) {
                                String nValue = allChildern.item(index).getChildNodes().item(0).getAttributes().getNamedItem("src").getNodeValue();
                            }
                        }
                    }
                }


            }
            currentStory.setDescription(description);
        }

但它不起作用


你几乎可以用kshPython做任何你可以用.grepsed awk

Python 还附带了一个非常大的库(就像 Java 和 C# 一样)和大量的附加模块,它们都还包括数据库的东西。

您不必学习 Python 就能成功编写脚本,大量的解决方案可以解决这个问题。但是 Python您的武器库中的有用武器。

底部,它非常能够处理大量任务,包括您提到的特定任务。

4

2 回答 2

5

描述元素包含一个 CDATA 节点。这意味着<img>您尝试访问的“元素”实际上只是一段文本(根本不是元素)。

您需要将文本解析为新的 XML 文档,以便通过 DOM 方法访问它。

于 2011-06-10T06:29:47.977 回答
0

警告:这可能有点脏,如果 xml 可以包含包含看起来像图像标签的内容的注释,它也可能很脆弱。

对具有 cdata 部分的短 xml 片段使用 xml 解析的替代方法是使用正则表达式获取图像 url。这是一个例子:

String xml = "<description><![CDATA[<div class=\"images\"><img src=\"http://www.voicetv.co.th/cache/images/8a1a6f2aeb7b0e9c1d6bb3eae314165f.jpg\"/></div>]]></description>";
Matcher matcher = Pattern.compile("<img src=\"([^\"]+)").matcher(xml);
while (matcher.find()) {
    System.out.println("img url: " + matcher.group(1));
}
于 2011-06-10T06:42:40.173 回答