2013-12-21 61 views
1
// 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文件我需要迭代XML缺少結束標籤?

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

回答

1

參考本教程在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"); 

其餘是相同的;趕上例外。

+0

Eggen我接受了你的答案,但是你能描述如何寫java 1.4嗎?可能嗎? – Suresh

+0

@Suresh即將到來的Java 8是如此的稚嫩;我希望你能夠在2014年切換。 –

0
<?php 
libxml_use_internal_errors(true); 
$sxe = simplexml_load_string("your XML code here!!"); 
if ($sxe === false) { 
    echo "Failed loading XML\n"; 
    foreach(libxml_get_errors() as $error) { 
    echo "\t", $error->message; 
    } 
} 
?> 

從Jenkov http://tutorials.jenkov.com/java-xml/stax-xmleventreader.html

+0

嘿,我已經嘗試過了......但我想知道我們是否可以在特定的XML文件中迭代缺少的結束標記? – Suresh

+0

我更新了答案 – Chaitanya