簡體   English   中英

在Java中解析沒有結束標記的XML

[英]Parsing XML with no closing tags in Java

我在解析沒有結束標記的XML時遇到了麻煩。 請參閱下面的xml片段。

我嘗試過SAX和StAX Parser,它們都需要帶有結束標記XXYY的正確格式的XML。...如您所見,XML格式略有不同...如果有任何API,請幫助我可以幫助我解析此問題,或者SAX / StAX是否可以幫助我實現我想要的...。

<Employees>
 <Employee>
  <Detail>
    <Date>2018014
    <Name>XXYY
    <Age>0
    <LANGUAGE>ENG
    <Manager>
    <MName>YYXX
    <MID>5959
    </Manager>
    <EmployeeID>1234
  </Detail>
 </Employee>
</Employees>

您可以通過添加所有缺少的結束標記來“修復” XML。

可以通過在行的末尾添加結束標簽來修復在同一行中標簽之后包含文本的任何開始標簽。

“包含文本”的規則可確保例如<Manager>標記不會結束,因為該標記實際上已向下3行結束。

工作代碼示例:

// Load file into memory
String xml = new String(Files.readAllBytes(Paths.get("test.xml")), StandardCharsets.UTF_8);

// Apply magic to add missing end-tags
xml = xml.replaceAll("(?m)^(\\s*)<(\\w+)>([^<]+)$", "$1<$2>$3</$2>");

// Parse then print the XML, to ensure there are no errors
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                          .parse(new InputSource(new StringReader(xml)));
TransformerFactory.newInstance().newTransformer()
                  .transform(new DOMSource(document), new StreamResult(System.out));

這似乎是SGML而不是XML。 我已經回答了一個較新的問題 (對於Javascript / node.js,但也與Java相關),詳細說明了如何使用OpenSP SGML軟件從SGML創建XML。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM