java中获取XML中的子xml_java - 使用Java获取XML子元素

我对XML的处理真的很糟糕,需要一些帮助。

这是我的XML文件的示例:<?xml version="1.0"?>

int

string

float

float

float

int

string

float

float

float

int

string

int

string

我需要打印每个资源和每个聚合器的子元素(id,类型,maxUsage等)。

这是我的方法:

public static Document createXMLDocument() throws IOException, Exception {

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder docBuilder = factory.newDocumentBuilder();

Document documento = docBuilder.parse(filepath);

documento.getDocumentElement().normalize();

return documento;

}

public static String[] readSubElementsXML() throws IOException, Exception

{

Document documento = createXMLDocument();

//gets XML elements

Element root = documento.getDocumentElement();

NodeList nListR = root.getElementsByTagName("resource");

NodeList nListA1 = root.getElementsByTagName("agregator1");

NodeList nListA0 = root.getElementsByTagName("agregator0");

ArrayList allNodes = appendNodeLists(nListR, nListA1, nListA0); //this method merges the 3 NodeLists into one ArrayList

int tam = allNodes.size();

String[] vec = new String[tam];

for (int i = 0; i < tam; i++) {

Element elem = (Element) allNodes.get(i);

vec[i] = elem.getAttribute("id");

System.out.println(""+vec[i]);

}

return vec;

}

有了这个,我只能得到属性ID,而我不需要它。我需要打印所有子元素,即使我将子元素添加到我的XML文件中,它也必须工作。

我怎样才能做到这一点?

最佳答案

元素是Node的子类。请参见Node#getChildNodes() javadoc。

一个包含此节点的所有子节点的NodeList。如果没有子节点,则这是一个不包含节点的NodeList。

然后,您可以遍历子节点,例如NodeList childNodes = elem.getChildNodes();

int childCount = childNodes.getLength();

Node childNode;

for (int i = 0; i < childCount; i++) {

childNode = childNodes.item(i);

// do things with the node

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值