XML child node attribute value

前端 未结 3 903
孤独总比滥情好
孤独总比滥情好 2020-12-16 08:05

I\'m trying to read xml file, ex :


    FEED TITLE
    5467sdad98787ad3149878sasda
    

        
3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 08:32

    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:

    
    
    
        FEED TITLE 1
        id1
        
          
        
    
    
        FEED TITLE 2
        id2
        
          
        
    
    
        id3
    
    
    

    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 entries = new ArrayList();
            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

    • package javax.xml.xpath
    • http://www.w3.org/TR/xpath
    • Wikipedia/XPath

提交回复
热议问题