我有一个简单的XML文件:
`<?xml: version = "1.0" ?>
<Company>
<Employee category = "technical">
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<ContactNo>123456789</ContactNo>
</Employee>
<Employee category = "non-technical">
<FirstName>Jane</FirstName>
<LastName>Doe</LastName>
<ContactNo>1234567898</ContactNo>
</Employee>
</Company>`
现在,我必须使用StAX解析XML,但无法获取属性。 我的代码是:
`public static void main(String[] args) throws XMLStreamException, FileNotFoundException {
XMLInputFactory xmlif = XMLInputFactory.newFactory();
Reader reader = new FileReader("Company.txt");
XMLStreamReader xmlsr = xmlif.createXMLStreamReader(reader);
while (xmlsr.hasNext()) {
switch (xmlsr.next()) {
case XMLStreamReader.START_ELEMENT:
System.out.println("START_ELEMENT");
System.out.println("Qname:" + xmlsr.getName());
break;
case XMLStreamReader.END_ELEMENT:
System.out.println("END_ELEMENT");
System.out.println("Qname:" + xmlsr.getName());
}
}
}`
当我开始阅读元素时,必须使用简单的IF函数检查元素中是否具有属性。如果它具有属性,我将使用:
for (int i = 0; i < xmlsr.getAttributeCount(); i++) {
String attributeName = xmlsr.getAttributeLocalName(i);
String attributeValue = xmlsr.getAttributeValue(i);
System.out.println("Attribute value for " + attributeName + " = " + attributeValue);
}
但是,我不知道将IF函数放在哪里以及如何检查它。 请有人可以插入IF函数的代码。 谢谢...
答案 0 :(得分:0)
已经有一段时间了,所以希望您自己得到答案:D
但是,如果您没有,这些属性将存储在START_ELEMENT中。这意味着添加属性打印代码的正确位置在case XMLStreamReader.START_ELEMENT
中,如下所示。
public static void main(String[] args) throws XMLStreamException, FileNotFoundException {
XMLInputFactory xmlif = XMLInputFactory.newFactory();
Reader reader = new FileReader("Company.txt");
XMLStreamReader xmlsr = xmlif.createXMLStreamReader(reader);
while (xmlsr.hasNext()) {
switch (xmlsr.next()) {
case XMLStreamReader.START_ELEMENT:
System.out.println("START_ELEMENT");
System.out.println("Qname:" + xmlsr.getName());
int numberOfAttributes = xmlsr.getAttributeCount();
if (numberOfAttributes > 0) {
for (int i = 0; i < numberOfAttributes; i++) {
String attributeName = xmlsr.getAttributeLocalName(i);
String attributeValue = xmlsr.getAttributeValue(i);
System.out.println("Attribute value for " + attributeName + " = " + attributeValue);
}
}
break;
case XMLStreamReader.END_ELEMENT:
System.out.println("END_ELEMENT");
System.out.println("Qname:" + xmlsr.getName());
break;
}
}
}