java怎么通过xml节点的属性获取这个节点的值

2024-10-29 22:40:27
推荐回答(4个)
回答1:

  1. 创建解析器
    SAXReader saxreader = new SAXReader();

  2. 读取文档
    Document doc = saxreader.read(new File("url"));

  3. 获取根
    Element root = doc.getRootElement();

  4. 获取子节点
    List list = root.elements();

  5. System.out.println(e.elementText("name"));
    System.out.println(e.element("score").attributeValue("java"));

  1. Reader reader = new InputStreamReader(con
    .getInputStream());
    SAXReader sax = new SAXReader();
    // sax.setEncoding("GBK");

  2. Document document = sax.read(reader);
    document.setXMLEncoding("GBK");
    Element root = document.getRootElement();
    // Document doc = reader.read(read);
    // Element root = doc.getRootElement();
    readNode(root, "");

  3. public static void readNode(Element root, String prefix) {
    if (root == null) return;
    // 获取属性
    List attrs = root.attributes();
    if (attrs != null && attrs.size() > 0) {
    System.err.print(prefix);
    for (Attribute attr : attrs) {
    System.err.print(attr.getValue() + " ");
    }
    System.err.println();
    }

  4. // 获取他的子节点
    List childNodes = root.elements();
    prefix += "\t";
    for (Element e : childNodes) {
    //输出内容
    System.err.println(e.getName()+":"+e.getData());
    readNode(e, prefix);
    }
    }

回答2:

SAXReader reader = new SAXReader();
            Document document = reader.read(new FileInputStream(f)); //dom4j读取
            String xpath = "/Record/Field[@name='Creator']";//查询属性type='Creator'
            Element element = (Element) document.selectSingleNode(xpath);//得到name=Creator的元素
            System.out.println(element.getText());

回答3:

//1. 创建解析器
SAXReader saxreader = new SAXReader();

//2. 读取文档
Document doc = saxreader.read(new File("url"));

//3. 获取根
Element root = doc.getRootElement();

//4. 获取子节点
List list = root.elements();

for(Element e : list){

System.out.println(e.elementText("name"));
System.out.println(e.element("score").attributeValue("java"));

}

回答4:

dom4j架包