[英]How to read and write XML File without certain nodes in Java
I am trying to read an XML File and write a new XML file without the first node(root element) and the second node. 我正在尝试读取XML文件并编写一个没有第一个节点(根元素)和第二个节点的新XML文件。 Here an example..
这是一个例子。
I got this: afile.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>
and want this : bfile.xml 并想要这个:bfile.xml
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
One way is to use XSLT, for instance XSLT 2.0 can do it with a simple stylesheet 一种方法是使用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>
You need to use an XSLT 2.0 processor like Saxon 9 to run the code given above. 您需要使用像Saxon 9这样的XSLT 2.0处理器来运行上面给出的代码。
If you don't know the name of the element you want to copy then using <xsl:copy-of select="/*/*/*" copy-namespaces="no"/>
instead of <xsl:copy-of select="//note" copy-namespaces="no"/>
should do. 如果您不知道要复制的元素的名称,则使用
<xsl:copy-of select="/*/*/*" copy-namespaces="no"/>
代替<xsl:copy-of select="//note" copy-namespaces="no"/>
。
Try the following ... 尝试以下方法...
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();
}
}
}
Output: 输出:
-------- 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>
Get the Conversion Box JAR for this ... 为此获取转换盒 JAR ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.