我正在解析 xml,但无法解析位于其他标签内的 xml 标签。 这是 XML 结构。
<Entry>
<MediaID>434234242342</MediaID>
<MediaName>Brazil</MediaName>
<PhoneNo>
<Ip>23232323232</Ip>
<Ip>32323232323</Ip>
<Ip>323232323232</Ip>
</PhoneNo>
</Entry>
这是 Java 代码。我成功地解析了 MediaID 和 MediaName,但是如何解析
中的标签Document doc = parser.getDomElement(return_string); // getting DOM element
NodeList nl2 = doc.getElementsByTagName("Entry");
for (int i = 0; i < nl2.getLength(); i++) {
Element e = (Element) nl2.item(i);
media_name = parser.getValue(e,"MediaName");
mediaID = parser.getValue(e,"MediaID");
phoneNo = parser.getValue(e,"PhoneNo"); //it is not working
}
最佳答案
尝试递归。您可以按照自己的方式格式化输出。
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class DOMParser {
public static void main(final String[] args) throws SAXException, IOException, ParserConfigurationException {
String xml = "<Entry>"
+ "<MediaID>434234242342</MediaID>"
+ "<MediaName>Brazil</MediaName>"
+ "<PhoneNo>"
+ "<Ip>23232323232</Ip>"
+ "<Ip>32323232323</Ip>"
+ "<Ip>323232323232</Ip>"
+ "</PhoneNo>"
+ "</Entry>";
DOMParser parser = new DOMParser();
final Document doc = parser.getDomElement(xml);
parser.parse(doc.getDocumentElement());
}
public void parse(final Element e) {
final NodeList children = e.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
final Node n = children.item(i);
if(n.getNodeType() == Node.TEXT_NODE){
System.out.println(n.getTextContent());
} else if (n.getNodeType() == Node.ELEMENT_NODE) {
System.out.print(n.getNodeName() + " : ");
parse((Element) n);
}
}
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
return null;
} catch (SAXException e) {
return null;
} catch (IOException e) {
return null;
}
return doc;
}
}
关于java - Android XML 解析 - 标签内有标签的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24613431/