简体   繁体   English

如何从xml文档中提取整个xml元素

[英]how to extract entire xml element from xml document

all the examples about parsing xml elements/nodes, that i've found, are about how to extract node attributes/values etc from xml document. 我发现的所有有关解析xml元素/节点的示例都是关于如何从xml文档中提取节点属性/值等的。

Im interested on how should i extract an entire element from opening tag to closing tag. 我对如何从开始标记到结束标记提取整个元素感兴趣。 Example: from xml document 示例:来自xml文档

<?xml version="1.0"?>
    <Employees>
        <Employee emplid="1111" type="admin"/>
    </Employees>

i would get the complete element 我会得到完整的元素

<Employee emplid="1111" type="admin"/>

to saving it in a String variable 将其保存在String变量中

Thanks in advance 提前致谢

You can either do the parsing yourself, or use Android's XML parser. 您可以自己进行解析,也可以使用Android的XML解析器。 This shows how to use the latter. 显示了如何使用后者。

If you use Android's parser you probably have to parse it completely, and then construct the string <Employee emplid="1111" type="admin"/> by hand. 如果您使用Android的解析器,则可能必须完全解析它,然后<Employee emplid="1111" type="admin"/>构造字符串<Employee emplid="1111" type="admin"/>

For now this is the best solution. 目前,这是最好的解决方案。

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

...

//xml document
String  xml = "<?xml version=\"1.0\"?><Employees><Employee emplid=\"1111\" type=\"admin\"/></Employees>";

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document document = parser.parse(new ByteArrayInputStream(xml.getBytes()));
//getting the target element
NodeList list=document.getElementsByTagName("Employee");
Node node=list.item(0);    

//writing the element in the string variable
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node), new StreamResult(buffer));
String str = buffer.toString();


System.out.println(str);

...

Inspired by this thread 受此线程启发

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM