我有XML文件,如下所示
<?xml version="1.0" encoding="utf-8"?>
<Movies>
<servername>
raaja
</servername>
<moviename>
xyz
</moviename>
<city>
Hyd
</city>
<theatername>
abc
</theatername>
<noofreels>
16
</noofreels>
<aspectratio>
216
</aspectratio>
</Movies>
我想要标签servername和theatername的值。休息,我不想要。如何使用java获取这些。是否可以使用标记名获取值。
答案 0 :(得分:1)
实现此目的的一种方法是使用JDK附带的DOM解析器。例如:
String url = getIntent().getStringExtra("webBrowserUrl");
webView.loadUrl(url);
使用StAX:
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
...
// Creates a new DOM parser instance.
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
// Parses XML and creates a DOM document object.
// The XML variable is your XML document above stored as a string, but you could
// easily read the contents from a file or database too.
Document document = documentBuilder.parse(new InputSource(new StringReader(XML)));
// Get the text content of <theatername> using the DOM API and print it to stdout.
String theaterName = document.getElementsByTagName("theatername").item(0).getTextContent().trim();
System.out.println(theaterName);