gpt4 book ai didi

java - 我需要迭代 xml 缺少结束标记吗?

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:29 24 4
gpt4 key购买 nike

 // Logic
XMLInputFactory factory = XMLInputFactory.newInstance();
Reader fileReader = new FileReader("1.xml");
XMLEventReader reader = factory.createXMLEventReader(fileReader);

while (reader.hasNext()) {
XMLEvent event = reader.nextEvent();
if (event.isStartElement()) {
StartElement element = (StartElement) event;
System.out.println("Start Element: " + element.getName());

Iterator iterator = element.getAttributes();
while (iterator.hasNext()) {
Attribute attribute = (Attribute) iterator.next();
QName name = attribute.getName();
String value = attribute.getValue();
System.out.println("Attribute name/value: " + name + "/" + value);
}
}
if (event.isEndElement()) {
EndElement element = (EndElement) event;
System.out.println("End element:" + element.getName());
}

if (event.isCharacters()) {
Characters characters = (Characters) event;
System.out.println("Text: " + characters.getData());
}
}

这里是示例 xml 文件

    <Bank>
<Account type="saving">
<Id>1001</Id>
<Name>Jack Robinson
<Number>7898998
<Amt>10000</Amt>
</Account>
</Bank>

最佳答案

在 Java 7 中:

Path xmlPath = Paths.get("1.xml");
byte[] bytes = Files.readAllBytes(xmpPath);
String xml = new String(bytes, StandardCharSets.ISO_8859_1);
xml = xml.replaceAll("^\\s*<(\w+)[^>]*>[^<]+$", "$0</$1>");
StringReader stringReader = new StringReader(xml);
XMLEventReader reader = factory.createXMLEventReader(stringReader);

这旨在替换包含单个标记的行,后跟一些内容。

我已经明确添加了编码。忽略它,会产生当前的平台编码,就像您的 FileReader 一样。 StandardCharSets,UTF_8一般来说适用于 XML,您可以检查:它是默认值,除非 <?xml ... encoding="..." ... ?> .

<小时/>

对于较旧的 Java:

File file = new File("1.xml");
int size = (int) file.length();
byte[] bytes = new byte[size];
FileInputStrea in = new FileInputStream(file);
in.read(bytes);
in.close();
String xml = new String(bytes, "ISO-8859-1");

其余相同;要捕获的异常。

关于java - 我需要迭代 xml 缺少结束标记吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20715860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com