java 如何遍历xml并输出每个节点的每个属性?
2个回答
展开全部
//打印xml文档
private void parseElement(Element root)
{
//System.out.print(root.getNamespaceURI());
System.out.print("<");
System.out.print(root.getNodeName());
//System.out.print(root.getPrefix());
//System.out.print(":");
//System.out.print(root.getLocalName());
NamedNodeMap nnm = root.getAttributes();
for(int i = 0; i < nnm.getLength(); i++)
{
Attr attr = (Attr)nnm.item(i);
System.out.print(" ");
System.out.print(attr.getName());
System.out.print("=\"");
System.out.print(attr.getValue());
System.out.print("\"");
}
System.out.print(">");
NodeList list = root.getChildNodes();
for(int i = 0; i < list.getLength(); i++)
{
Node node = list.item(i);
if(node instanceof Element)
{
Element e = (Element)node;
parseElement(e);
}
else if(node instanceof Text)
{
Text t = (Text)node;
System.out.print(t.getNodeValue());
}
}
System.out.print("</");
System.out.print(root.getNodeName());
System.out.print(">");
}
private void parseRootName()
{
Element root = doc.getDocumentElement();
System.out.println(root.getNodeName());
}
//工厂
private void getDocument()
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder db = factory.newDocumentBuilder();
doc = db.parse(new File(fileName));
}
catch(Exception ex)
{
ex.printStackTrace();
System.exit(1);
}
}
private void parseElement(Element root)
{
//System.out.print(root.getNamespaceURI());
System.out.print("<");
System.out.print(root.getNodeName());
//System.out.print(root.getPrefix());
//System.out.print(":");
//System.out.print(root.getLocalName());
NamedNodeMap nnm = root.getAttributes();
for(int i = 0; i < nnm.getLength(); i++)
{
Attr attr = (Attr)nnm.item(i);
System.out.print(" ");
System.out.print(attr.getName());
System.out.print("=\"");
System.out.print(attr.getValue());
System.out.print("\"");
}
System.out.print(">");
NodeList list = root.getChildNodes();
for(int i = 0; i < list.getLength(); i++)
{
Node node = list.item(i);
if(node instanceof Element)
{
Element e = (Element)node;
parseElement(e);
}
else if(node instanceof Text)
{
Text t = (Text)node;
System.out.print(t.getNodeValue());
}
}
System.out.print("</");
System.out.print(root.getNodeName());
System.out.print(">");
}
private void parseRootName()
{
Element root = doc.getDocumentElement();
System.out.println(root.getNodeName());
}
//工厂
private void getDocument()
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder db = factory.newDocumentBuilder();
doc = db.parse(new File(fileName));
}
catch(Exception ex)
{
ex.printStackTrace();
System.exit(1);
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
大家,你弄点分,引鱼上钩啊
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询