![](/img/trans.png)
[英]How to read xml file with multiple sub nodes in java with SAX parser
[英]How to read and write XML File without certain nodes in Java
我正在嘗試讀取XML文件並編寫一個沒有第一個節點(根元素)和第二個節點的新XML文件。 這是一個例子。
我得到了:afile.xml
<soap:Envelope>
<soap:Body>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
</soap:Body>
</soap:Envelope>
並想要這個:bfile.xml
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
一種方法是使用XSLT,例如XSLT 2.0可以使用簡單的樣式表來實現
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:template match="/">
<xsl:copy-of select="//note" copy-namespaces="no"/>
</xsl:template>
</xsl:stylesheet>
您需要使用像Saxon 9這樣的XSLT 2.0處理器來運行上面給出的代碼。
如果您不知道要復制的元素的名稱,則使用<xsl:copy-of select="/*/*/*" copy-namespaces="no"/>
代替<xsl:copy-of select="//note" copy-namespaces="no"/>
。
嘗試以下方法...
import java.util.Map;
import cjm.component.cb.map.ToMap;
import cjm.component.cb.xml.ToXML;
public class NoteExtract
{
public static void main(String[] args)
{
try
{
String xml = "<soap:Envelope><soap:Body><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note></soap:Body></soap:Envelope>";
Map<String, Object> map = new ToMap().convertToMap(xml);
Map<String, Object> mapEnvelope = (Map<String, Object>) map.get("soap:Envelope");
Map<String, Object> mapBody = (Map<String, Object>) mapEnvelope.get("soap:Body");
String extractedXML = (new ToXML().convertToXML(mapBody, true)).toString();
System.out.println("Extracted XML: " + extractedXML);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
輸出:
-------- XML Detected --------
-------- Map created Successfully --------
-------- Map Detected --------
-------- XML created Successfully --------
Extracted XML: <note><to>Tove</to><body>Don't forget me this weekend!</body><from>Jani</from><heading>Reminder</heading></note>
為此獲取轉換盒 JAR ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.