So I have been asking questions here trying to get the answer for myself but I just cant get it to work without running into a new error. If anyone can help me I would appreciate it. I want to replace this portion
"<a>\n" +
"<b>\n" +
"<c id=\"00001\" time=\"1:00\" day=\"Friday\" name1=\"John\" name2=\"Mary\"></c>\n" +
"<c id=\"00002\" time=\"2:00\" day=\"Monday\" name1=\"Ed\" name2=\"Kate\"></c>\n" +
"<c id=\"00003\" time=\"3:00\" day=\"Sunday\" name1=\"Mary\" name2=\"Ed\"></c>\n" +
"<c id=\"00004\" time=\"4:00\" day=\"Friday\" name1=\"Kate\" name2=\"John\"></c>\n" +
"</b>\n" +
"</a>"
with a XML url instead, as that information will be pulled from a server as the data changes.
Here is the source as you can see what I am trying accomplish once I have the data from the xml file. It works fine as it is, but whenever I try and implement a url as the InputSource I get tons of errors that no matter what ive tried does not resolve the problem.
package com.newxpath;
import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class NewxpathActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InputSource xml = new InputSource(new StringReader("<a>\n" +
"<b>\n" +
"<c id=\"00001\" time=\"1:00\" day=\"Friday\" name1=\"John\" name2=\"Mary\"></c>\n" +
"<c id=\"00002\" time=\"2:00\" day=\"Monday\" name1=\"Ed\" name2=\"Kate\"></c>\n" +
"<c id=\"00003\" time=\"3:00\" day=\"Sunday\" name1=\"Mary\" name2=\"Ed\"></c>\n" +
"<c id=\"00004\" time=\"4:00\" day=\"Friday\" name1=\"Kate\" name2=\"John\"></c>\n" +
"</b>\n" +
"</a>"));
String name = "Ed";
XPath xpath = XPathFactory.newInstance().newXPath();
String expr = String.format("//a/b/c[@name2='%s']", name);
Node c = null;
try {
c = (Node) xpath.evaluate(expr, xml, XPathConstants.NODE);
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NamedNodeMap attribs = c.getAttributes();
String id = attribs.getNamedItem("id").getNodeValue();
String time = attribs.getNamedItem("time").getNodeValue();
// etc.
EditText id2 = (EditText) findViewById(R.id.id2);
EditText time2 = (EditText) findViewById(R.id.time2);
id2.setText(String.valueOf(id));
time2.setText(String.valueOf(time));
}
}
You probably need to add the INTERNET permission to your AndroidManifest.xml file (I assume from the Android imports that this is taking place on Android). Otherwise I don’t see why this wouldn’t work. I copied your XML to the URL http://pastebin.com/raw.php?i=RF8cL5YZ and then ran it against the following code at a command line and it worked just fine.