我需要编写一个简单的函数来在java上使用DOM解析来自Url的xml。 这是xml url。
如果我将其写入/assets/exampleXML.xml并使用此代码,则一切正常。
static final String NODE_EMP = "Record";
static final String NODE_NAME = "Nominal";
static final String NODE_SALARY = "Value";
.....
public void onBtnClick3(View v) {
XMLDOMParser parser = new XMLDOMParser();
try {
InputStream is = getAssets().open("exampleXML2.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
NodeList nodeList = doc.getElementsByTagName(NODE_EMP);
for (int i = 0; i < nodeList.getLength(); i++) {
Element e = (Element) nodeList.item(i);
nameText.append(parser.getValue(e, NODE_NAME) + "\n");
nameText.append(parser.getValue(e, NODE_SALARY) + "\n");
}
但如果我换到
public static final String QUERY_URL = "http://www.cbr.ru/scripts/XML_dynamic.asp?......";
public void onBtnClick(View v) {
XMLDOMParser parser = new XMLDOMParser();
try {
URL url = new URL(QUERY_URL);
URLConnection conn = url.openConnection();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(conn.getInputStream());
这不起作用。有什么问题以及如何解决? 我已经读过了,但它不起作用。请帮帮我。 How to read XML response from a URL in java?
答案 0 :(得分:0)
我不喜欢手工解析XML,我通常使用POJO和简单的XML来为我工作。以下是使用Volley进行http通信和Simple XML
的示例的POJO
substr
UnitTest
function get_string_between($string, $start, $end) {
// make sure we escape all parts of the pattern
$start = preg_quote($start, '/');
$end= preg_quote($end, '/');
// create the pattern
$pattern = "/$start(.*?)$end/su"; // using s and u pattern modifiers
if (preg_match($pattern, $string, $match)) {
return $match[1];
}
}
$str = <<<'STR'
تفاحة:
<br><img src="http://asite.com/1.jpg"><br>
<a href="https://asite.com/1.html">تفاحة</a> <br />
<a href="http://asite.com/link.html">link1 </a> <br />
<a href="http://asite.com/link.html">link2 </a> <br />
<a href="http://asite.com/link.html">link3 </a> <br />
<a href="http://asite.com/link.html">link4 </a> <br />
<a href="http://asite.com/link.html">link5 </a> <br />
--------------------------------------<br>
STR;
$start = 'تفاحة:';
$end = '--------------------------------------<br>';
var_dump(get_string_between($str, $start, $end));
/*
output
string(380) "
<br><img src="http://asite.com/1.jpg"><br>
<a href="https://asite.com/1.html">تفاحة</a> <br />
<a href="http://asite.com/link.html">link1 </a> <br />
<a href="http://asite.com/link.html">link2 </a> <br />
<a href="http://asite.com/link.html">link3 </a> <br />
<a href="http://asite.com/link.html">link4 </a> <br />
<a href="http://asite.com/link.html">link5 </a> <br />
"
*/