我必须逐行读取java中的Xml文件。
该文件包含以下格式的行:
<CallInt xsi:type="xsd:int">124</CallInt>
我只需要从上面的行中选择标记名称CallInt和值124。 我尝试使用String Tokenizer,Split等。但没有什么可以帮助的。
任何人都可以帮我吗?
一些代码
BufferedReader buf = new BufferedReader(new FileReader(myxmlfile));
while((line = buf.readLine())!=null)
{
String s = line;
// Scanning for the tag and the integer value code???
}
答案 0 :(得分:0)
你应该使用一个小的xml解析器。
如果你必须逐行阅读,并且格式保证是基于行的,请使用indexOf()搜索要提取的内容周围的分隔符,然后使用substring()...
int cut0 = line.indexOf('<');
if (cut0 != -1) {
int cut1 = line.indexOf(' ', cut0);
if (cut1 != -1) {
String tagName = line.substring(cut0 + 1, cut1);
int cut2 = line.indexOf('>', cut1); // insert more ifs as needed...
int cut3 = line.indexOf('<', cut2);
String value = line.substring(cut2 + 1, cut2);
}
}
答案 1 :(得分:0)
以下是StaX的一个小例子。
注意为简单起见,我删除了对架构的引用(否则会失败)。
名为“test”的XML文件,位于路径“/ your / path”
<thingies>
<thingie foo="blah"/>
<CallInt>124</CallInt>
</thingies>
<强>代码强>
XMLInputFactory factory = null;
XMLStreamReader reader = null;
// code is Java 6 style, no try with resources
try {
factory = XMLInputFactory.newInstance();
// coalesces all characters in one event
factory.setProperty(XMLInputFactory.IS_COALESCING, true);
reader = factory.createXMLStreamReader(new FileInputStream(new File(
"/your/path/test.xml")));
boolean readCharacters = false;
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case (XMLStreamConstants.START_ELEMENT): {
if (reader.getLocalName().equals("CallInt")) {
readCharacters = true;
}
break;
}
case (XMLStreamConstants.CHARACTERS): {
if (readCharacters) {
System.out.println(reader.getText());
readCharacters = false;
}
break;
}
}
}
}
catch (Throwable t) {
t.printStackTrace();
}
finally {
try {
reader.close();
}
catch (Throwable t) {
t.printStackTrace();
}
}
<强>输出强>
124
Here是关于模式和StaX的一个有趣的SO线程。