如何获取XML中的属性

时间:2011-07-28 07:33:50

标签: java xml

感谢以前的回复。

我正在使用java(SAXParser)解析XML文件,我不知道如何使用属性值解析属性值(元数据)。我给出了两个主要的类别 <category name="XYZ" /> <category name="ABC"/>

            <subcategory name="" loc="C://program files" link="www.sample.com" parentnode="XYZ"/>
            <subcategory name="" loc="C://program files" link="http://" parentnode="ABC"/>`

在子类别中,我已将主类别与parentnode属性相关联。我的问题是我想获得所有仅包含特定父属性的属性。 (例如)我想要所有属性仅存在于父属性“ABC”中。这有可能获得一个价值。

3 个答案:

答案 0 :(得分:4)

以下代码是否可以解决您的问题?

XML

<?xml version="1.0"?>
<categories>
    <category name="ABC">
        <subcategory name="123" 
            loc="C://program files" 
            link="www.sample.com" 
            parentnode="ABC"/>
        <subcategory name="456" 
            loc="C://program files" 
            link="http://" 
            parentnode="ABC"/>
    </category>

    <category name="XYZ"> 
        <subcategory name="123" 
            loc="C://program files" 
            link="www.sample.com" 
            parentnode="XYZ"/>
        <subcategory name="456" 
            loc="C://program files" 
            link="http://abc.com" 
            parentnode="XYZ"/>
    </category>
</categories>

JAVA

package com.stackoverflow;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Question6855476 {
private static final String CFG_XML_PATH = "D:\\sample\\path\\question6855476.xml";
private static final String searchArg = "ABC";

public static void main(String[] args) {

    List locList = getLocsByCategoryName(searchArg);
    List linkList = getLinksByCategoryName(searchArg);

    printCollection(locList,"LOC");
    printCollection(linkList,"LINKS");

}

private static void printCollection(List locList, String string) {
    System.out.println();
    System.out.println("### Collection: "+string+"\n");
    if(locList.isEmpty()) {
        System.out.println("\tNo items. Collection is empty.");
    } else {
        for(Object obj: locList) {
            System.out.println("\t"+obj);
        }
    }

}

private static List getLocsByCategoryName(String catName) {
    if(null==catName||catName.length()<=0) {
        System.out.println("ERROR: catName is null/blank");
        return Collections.EMPTY_LIST;
    } else {
        return getSubcatAttrValuesByAttrName("loc", catName);
    }
}

private static List getLinksByCategoryName(String catName) {
    if(null==catName||catName.length()<=0) {
        System.out.println("ERROR: catName is null/blank");
        return Collections.EMPTY_LIST;
    } else {
        return getSubcatAttrValuesByAttrName("link", catName);
    }
}

private static List<Object> getSubcatAttrValuesByAttrName(String attrName, String catName) {

    List<Object> list = new ArrayList<Object>();

    if(null==attrName||attrName.length()<=0) {
        System.out.println("ERROR: attrName is null/blank");
    } else {
        try {
              File file = new File(CFG_XML_PATH);
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              DocumentBuilder db = dbf.newDocumentBuilder();
              Document doc = db.parse(file);
              doc.getDocumentElement().normalize();

              NodeList catLst = doc.getElementsByTagName("category");

              for (int i = 0; i < catLst.getLength(); i++) {

                  Node cat = catLst.item(i);

                  NamedNodeMap catAttrMap = cat.getAttributes();
                  Node catAttr = catAttrMap.getNamedItem("name");

                  if(catName.equals(catAttr.getNodeValue())){ // CLUE!!!

                      NodeList subcatLst = cat.getChildNodes();

                      for (int j = 0; j < subcatLst.getLength(); j++) {
                          Node subcat = subcatLst.item(j);
                          NamedNodeMap subcatAttrMap = subcat.getAttributes();

                          if(subcatAttrMap!=null) {
                              Node subcatAttr = subcatAttrMap.getNamedItem(attrName);
                              list.add(subcatAttr.getNodeValue());
                          }
                      }
                  }
              }
        } catch (Exception e) { // FIXME
            e.printStackTrace();
        }
    }
    return list;
}

}

我基于this article

答案 1 :(得分:3)

我假设您想要获得subcategory元素的所有属性parentnode属性值等于“ABC”?那么你想在你给出的例子中得到属性(name="" loc="C://program files" link="http://" parentnode="ABC")吗?

基本的解析代码应如下所示:

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
MySAXHandler handler = new MySAXHandler();
handler.setDesireParentNodeAttributeValue("ABC");
parser.parse(xmlInputStream, handler);

/* 
 *this list contains all the attributes of the subcategory element that has
 * parentnode attribute equals to "ABC"
 */
List<Attributes> whatIWant = handler.getDesireAttributes();

//do whatever you wnat with "whatIWant"

....

public class MySAXHandler extends DefaultHandler2
{
    private String desirePrentNodeAttributeValue;
    private List<Attributes> desireAttributes = new ArrayList<Attributes>();

    public void setDesireParentNodeAttributeValue(String val)
    {
        this.desirePrentNodeAttributeValue = val;
    }

    public List<Attributes> getDesireAttributes()
    {
        return desireAttributes;
    }

    public void startElement(String uri,
                         String localName,
                         String qName,
                         Attributes attributes)
    throws SAXException
    {
        if ("subcategory".equals(localName)
            && attributes
                .getValue("parentnode")
                .equals(this.desirePrentNodeAttributeValue))
        {
             desireAttributes.add(attributes);
        }
    }
}

答案 2 :(得分:0)

一旦解析了XML,您就可以浏览数据以找到所需内容,但更好的方法可能是使用XPath来查询XML。

有一些教程材料here