Java 获取所有元素

Java 获取所有元素,java,xml,sax,Java,Xml,Sax,我有一个XML文档,看起来像这样(我知道,它没有意义,只是一个示例): 获取第一个参数的第一个属性name的内容 String country = doc.getElementsByTagName("Country").item(0).getTextContent(); String name = source.getElementsByTagName("Param").item(0).getAttributes().item(0).getNodeValue(); 但是,在不知道存在多少Pa

我有一个XML文档,看起来像这样(我知道,它没有意义,只是一个示例):

获取第一个
参数的第一个属性
name
的内容

String country = doc.getElementsByTagName("Country").item(0).getTextContent();
String name = source.getElementsByTagName("Param").item(0).getAttributes().item(0).getNodeValue();
但是,在不知道存在多少
Param
元素的情况下,如何获取
Param
的所有属性的所有值呢

我需要类似(“伪代码”)的东西:

HashMap hm=newhashmap();

对于(inti=0;i,您可以通过属性名称来请求属性

String attrName = source.getElementsByTagName("Param").item(i).getAttribute("name"));
String value = source.getElementsByTagName("Param").item(i).getAttribute("value"));
//you could test if the values are null
hm.put(attrName, value);
HashMap hm=newhashmap();
SAXReader=新SAXReader();
documentdocument=reader.read(“yourxmlfilehere(url,文件)”;
root=document.getRootElement();
根=根元素(“人”);
for(迭代器i=root.elementIterator(“Param”);i.hasNext();)
{
元素e=(元素)i.next();
hm.put(e.attributeValue(“名称”),e.attributeValue(“价值”);
}

使用dom4j解析XML文档尝试使用我文章中的代码应该可以。使用dom4j库解析XML解析器。谢谢,但那只是伪代码。
getElementsByTagName
中没有size()-方法。节点列表上有一个getLength()函数
HashMap<String, String> hm = new HashMap<String, String>();

for(int i=0; i<=source.getElementsByTagName("Param").size(); i++){
  String name = source.getElementsByTagName("Param").item(i).getAttributes().item(0).getNodeValue();
  String value = source.getElementsByTagName("Param").item(i).getAttributes().item(1).getNodeValue();

  hm.put(name, value);
}
String attrName = source.getElementsByTagName("Param").item(i).getAttribute("name"));
String value = source.getElementsByTagName("Param").item(i).getAttribute("value"));
//you could test if the values are null
hm.put(attrName, value);
    HashMap<String, String> hm = new HashMap<String, String>();
    SAXReader reader = new SAXReader();
    Document document = reader.read("yourxmlfilehere(url, file)");
    root = document.getRootElement();
    root = root.element("Person");
    for(Iterator i = root.elementIterator("Param"); i.hasNext();)
    {
        Element e = (Element)i.next();
        hm.put(e.attributeValue("name"), e.attributeValue("value"));
    }