假设我的XML看起来像这样
<?xml version="1.0"?>
<Employees>
<Employee>
<name>Pankaj</name>
<age>29</age>
<role>Java Developer</role>
<gender>Male</gender>
<address>
<flat>f 09</flat>
<housenum>naksha atlantis</housenum>
<area>E city</area>
</address>
<ContactDetails>
<mobile>4676543565</mobile>
<landline>0120-223312</landline>
</ContactDetails>
</Employee>
</Employee>
<Employee>
<name>Lisa</name>
<age>35</age>
<role>CSS Developer</role>
<gender>Female</gender>
<addressLine>
<local>f 03</local>
<gate>149</gate>
<area>domlur</area>
</addressLine>
</Employee>
</Employees>
**I want output in this format**
[员工[员工[姓名,年龄,角色,性别,地址[单位,房屋编号,区域],ContactDetails [移动电话,座机]]]]] [Employees [Employee [Employee [name,age,role,gender,addressaddress2 [local2,gate2,area2]]]] ##
答案 0 :(得分:0)
我将在每个startElement
事件中使用Java SAX和日志元素名称。
here是一个很好的例子。
答案 1 :(得分:0)
请注意,您的示例XML格式不正确,原因是第一位员工之后重复了</Employee>
标签。
假设您不知道XML模式并且可以将XML加载到内存中,则可以使用Dom4j并创建一个递归函数来检查元素:
public static void main(String[] args) throws Exception {
SAXReader reader = new SAXReader();
Document doc = reader.read(Main.class.getResourceAsStream("/input.xml"));
iterate(doc.getRootElement(), 0);
}
private static void iterate(Element el, int level) {
System.out.print(" ".repeat(level));
System.out.println(el.getName());
el.elements().forEach(e -> iterate(e, level + 1));
}
将输出:
Employees
Employee
name
age
role
gender
address
flat
housenum
area
ContactDetails
mobile
landline
Employee
name
age
role
gender
addressLine
local
gate
area
答案 2 :(得分:0)
您可以使用JDK1.4及更高版本中包含的org.w3c.dom并执行以下操作:
private static String parse(Node n) {
if(n.getChildNodes().getLength() <= 2) return n.getNodeName();
String res = n.getNodeName() + "[";
NodeList children = n.getChildNodes();
for(int i = 1 ; i < children.getLength() ; i += 2) {
res += parse(children.item(i)) + ",";
}
return res.substring(0, res.length() - 1) + "]";
}
public static void main(String[] args) throws Exception {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("data.xml"));
doc.getDocumentElement().normalize();
System.out.println("[" + parse(doc.getFirstChild()) + "]");
}
给出输出:
Employees[Employee[name,age,role,gender,address[flat,housenum,area],ContactDetails[mobile,landline]],Employee[name,age,role,gender,addressLine[local,gate,area]]]]