java - java中解析xml字符串

标签 java xml dom xml-parsing xmldocument

我一直在尝试使用从其他帖子中找到的代码来解析 xml 字符串,但是当尝试获取节点元素时,我不断获取空值。有人可以看到错误或我缺少的东西吗?

try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder  db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(post));

    Document doc;
    try {

        doc = db.parse(is);
        doc.getDocumentElement().normalize();
        Element root = doc.getDocumentElement();
        NodeList nodes = root.getElementsByTagName("entry");


    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

根元素为空,节点列表也为空。 XML 帖子开头为:

<entry xmlns="http://www.w3.org/2005/Atom" 
xmlns:activity="http://activitystrea.ms/spec/
1.0/"    xmlns:service="http://activitystrea.ms/ 
service-provider"    xmlns:thr="http://purl.org/syndication/thread/1.0" 
xmlns:gnip="http://www.post.com/schemas/2010" 
 xmlns:geo="http://www.georss.org/georss" xmlns:poco="http://portablecontacts.net/spec/1.0">
 <id>...

编辑:

NodeList nodes.. //The value of the local nodes is not used
[entry: null]  
// it skips the following lines...
for(int i=0; i < nodes.getLength() - 1; i++){
        System.out.println(nodes.item(i).toString());   
        }

最佳答案

替换 NodeList 节点 = root.getElementsByTagName("entry");

by NodeList 节点 = root.getChildNodes();

关于java - java中解析xml字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25493605/

相关文章:

java - 数组按字母顺序排序

c# - 在将数据从 Excel 文件转换为 XML 时,点被隐式转换为散列

javascript - 使用 Javascript 显示表格会在 for 循环中中断

javascript - Angular 5 [隐藏] 没有完全工作

java - 选择正确版本的 Apache Commons Logging

java - 使用魔数(Magic Number) (1) 或全局常量检查列表大小?

javascript - 处理服务器 XML 响应

javascript - 无需太多 jQuery 请求即可获取传递的元素属性和属性

没有辅助变量,Javac 无法推断类型

java - RuntimeException : Unable to start activity ComponentInfo: java. lang.NullPointerException 致命异常