我想將xml解析爲鍵值對的映射,如下所示。使用DocumentBuilder進行XML解析
示例XML文檔:
<Students>
<StudentA>
<Id>123</Id>
<Address>123 W </Address>
<Courses>
<Course1>CS203</Course1>
<Course2>CS206</Course2>
</Courses>
</StudentA>
<StudentB>
<Id>124</Id>
<Address>124 W </Address>
<Courses>
<Course1>CS202</Course1>
<Course2>CS204</Course2>
</Courses>
</StudentB>
</Students>
XML解析器代碼:
/**
* Parse the given xml data.
* @param xmlString The xml string to be parsed.
* @return Non-null list of {@link DiscreteDataEntry} values, may be empty.
*/
Map<String, String> parseXML(final String xmlString)
{
final String xmlDataToParse = xmlString;
parentNode = "";
try
{
final InputStream inputStream = new ByteArrayInputStream(xmlDataToParse.getBytes());
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
final Document document = documentBuilder.parse(inputStream);
final Map<String, String> data = createMapOfAttributeValuesKeyedByName(document.getDocumentElement());
}
catch (final Exception exception)
{
System.out.println("Exception:" + exception);
}
return data;
}
/**
* A recursive method which will loop through all the xml nodes.
* @param node The node.
* @return Non-null map of test values keyed by test name, may be empty.
*/
Map<String, String> createMapOfAttributeValuesKeyedByName(final Node node)
{
final Map<String, String> attributeValuesKeyedByName = new LinkedHashMap<String, String>();
final NodeList nodeList = node.getChildNodes();
for (int index = 0; index < nodeList.getLength(); index++)
{
final Node currentNode = nodeList.item(index);
if (node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.ELEMENT_NODE)
{
parentNode = getAncestralOrigin(currentNode);
attributeValuesKeyedByName.putAll(createMapOfAttributeValuesKeyedByName(currentNode));
}
else if (node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.TEXT_NODE)
{
final String attributeName = parentNode.length() > 0 ? parentNode + "." + node.getNodeName().trim() : node.getNodeName().trim();
final String attributeValue = node.getTextContent().trim();
attributeValuesKeyedByName.put(attributeName, attributeValue);
parentNode = "";
}
}
return attributeValuesKeyedByName;
}
/**
* Parses a give node and finds all its ancestors.
* @param node The node whose ancestors have to be found.
* @return A non-null but possible empty string built using the ancestors of the node.
*/
final String getAncestralOrigin(final Node node)
{
String ancestralOrigin = "";
final Node currentParentNode = node.getParentNode();
if (currentParentNode != null && currentParentNode.getNodeType() != Node.DOCUMENT_NODE)
{
ancestralOrigin = currentParentNode.getNodeName();
final String ancestor = getAncestralOrigin(currentParentNode);
if (ancestor.length() > 0)
{
ancestralOrigin = ancestor + "." + ancestralOrigin;
}
}
return ancestralOrigin;
}
地圖的輸出是:
Key:[Students.StudentA.Id], Value:[123]
Key:[Students.StudentA.Address], Value:[123 W]
Key:[Students.StudentA.Courses.Course1], Value:[CS203]
Key:[Students.StudentA.Courses.Course2], Value:[CS206]
Key:[Students.StudentB.Id], Value:[124]
Key:[Students.StudentB.Address], Value:[124 W]
Key:[Students.StudentB.Courses.Course1], Value:[CS202]
Key:[Students.StudentB.Courses.Course2], Value:[CS204]
但這輸出工作正常,如果該文件是正在閱讀
final BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(url.getFile().replaceAll("%20", " "))));
如果同一個文件中被讀出以
DataInputStream is = new DataInputStream(new FileInputStream(new File(url.getFile().replaceAll("%20", " "))));
輸出是不同的。它確實在xml文檔中使用了所有的CR和LF。
鍵:[學生],值:123 123W¯¯
CS203
CS206
124
124 W
CS202
CS204]
我使用的是依賴罐子閱讀這DataInputStream所使用的XML文件。
我總是覺得我的xml解析器會照顧CR/LF/NewLine看起來不像它。 我將在分析之前用空字符串替換所有CR LF和NewLines。
但我想知道是否有其他的XML解析器會自己照顧自己。還有什麼是BufferedReader跳過CR/LF和NewLine 的原因,但DataInputStream不會。
還有沒有其他更好的方法來找到子標籤的祖先,我需要他們使關鍵值獨一無二。
xml將保持原樣並且無法更改。此外,XML將不會像這裏顯示的那樣,它將是一個帶有標籤 更改的通用XML,所以我正在嘗試製作一個通用的XML解析器,用於解析xml子標記並將它們放入地圖中。
孩子標籤可以重複,所以我使用孩子的路徑使其獨特。
也有一種方法來解析xml只有這些標籤(StudentA/StudentB)通過刪除父標籤學生遞歸。
注意:xml格式發生變化,我解析的xml可能會更改爲每個xml文件。 所以我真的不能解析像得到StudentA的孩子。
此示例源代碼可能是一個好開始:http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/在格式更改的情況下,你可以檢查空的節點,只是它返回一個0. – WilliamShatner
我可以告訴你,vtd-xml肯定會照顧你的CR/LF。 –