Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

java - XML child node attribute value

I'm trying to read xml file, ex :

<entry>
    <title>FEED TITLE</title>
    <id>5467sdad98787ad3149878sasda</id>
    <tempi type="application/xml">
      <conento xmlns="http://mydomainname.com/xsd/radiofeed.xsd" madeIn="USA" />
    </tempi>
</entry>

Here is the code I have so far :

Here is my attempt of trying to code this, what to say not successful thats why I started bounty. Here it is http://pastebin.com/huKP4KED .

Bounty update :

I really really tried to do this for days now didn't expect to be so hard, I'll accept useful links/books/tutorials but prefer code because I need this done yesterday.

Here is what I need:

Concerning xml above :

  • I need to get value of title, id
  • attribute value of tempi as well as madeIn attribute value of contento

What is the best way to do this ?

EDIT:

@Pascal Thivent

Maybe creating method would be good idea like public String getValue(String xml, Element elementname), where you specify tag name, the method returns tag value or tag attribute(maybe give it name as additional method argument) if the value is not available

What I really want to get certain tag value or attribute if tag value(s) is not available, so I'm in the process of thinking what is the best way to do so since I've never done it before

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The best solution for this is to use XPath. Your pastebin is expired, but here's what I gathered. Let's say we have the following feed.xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<entries>
<entry>
    <title>FEED TITLE 1</title>
    <id>id1</id>
    <tempi type="type1">
      <conento xmlns="dontcare?" madeIn="MadeIn1" />
    </tempi>
</entry>
<entry>
    <title>FEED TITLE 2</title>
    <id>id2</id>
    <tempi type="type2">
      <conento xmlns="dontcare?" madeIn="MadeIn2" />
    </tempi>
</entry>
<entry>
    <id>id3</id>
</entry>
</entries>

Here's a short but compile-and-runnable proof-of-concept (with feed.xml file in the same directory).

import javax.xml.xpath.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
import java.util.*;

public class XPathTest {
    static class Entry {
        final String title, id, origin, type;
        Entry(String title, String id, String origin, String type) {
            this.title = title;
            this.id = id;
            this.origin = origin;
            this.type = type;
        }
        @Override public String toString() {
            return String.format("%s:%s(%s)[%s]", id, title, origin, type);
        }
    }

    final static XPath xpath = XPathFactory.newInstance().newXPath();
    static String evalString(Node context, String path) throws XPathExpressionException {
        return (String) xpath.evaluate(path, context, XPathConstants.STRING);
    }

    public static void main(String[] args) throws Exception {
        File file = new File("feed.xml");
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
        NodeList entriesNodeList = (NodeList) xpath.evaluate("//entry", document, XPathConstants.NODESET);

        List<Entry> entries = new ArrayList<Entry>();
        for (int i = 0; i < entriesNodeList.getLength(); i++) {
            Node entryNode = entriesNodeList.item(i);
            entries.add(new Entry(
                evalString(entryNode, "title"),
                evalString(entryNode, "id"),
                evalString(entryNode, "tempi/conento/@madeIn"),
                evalString(entryNode, "tempi/@type")
            ));
        }
        for (Entry entry : entries) {
            System.out.println(entry);
        }
    }
}

This produces the following output:

id1:FEED TITLE 1(MadeIn1)[type1]
id2:FEED TITLE 2(MadeIn2)[type2]
id3:()[]

Note how using XPath makes the value retrieval very simple, intuitive, readable, and straightforward, and "missing" values are also gracefully handled.

API links


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...