I have one local xml file. I am storing here : res/xml/myxml.xml
<?xml version="1.0" encoding="utf-8"?>
<list>
<lists>
<tag>College Website</tag>
<value>http://www.nitk.ac.in/</value>
<lastupdate>04-07-2012</lastupdate>
</lists>
<lists>
<tag>College Images</tag>
<value>http://studentsworld.nitk.ac.in/index.php?q=convocation.html</value>
<lastupdate>25-9-2011</lastupdate>
</lists>
</list>
I have doc for loop. but how to connect local xml file in doc parser. i don't want url model, i want to a local xml file.
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
tag[i] = new TextView(this);
value[i] = new TextView(this);
lastupdate[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("tag");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
tag[i].setText("tag = " + ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("value");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
value[i].setText("value = " + ((Node) websiteList.item(0)).getNodeValue());
NodeList lastupdateList = fstElmnt.getElementsByTagName("tag");
Element lastupdateElement = (Element) lastupdateList.item(0);
lastupdateList = lastupdateElement.getChildNodes();
lastupdate[i].setText("lastupdate = " + ((Node) lastupdateList.item(0)).getNodeValue());
layout.addView(tag[i]);
layout.addView(value[i]);
layout.addView(lastupdate[i]);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
I have main.xml file
please send me a code
put you XML file in assets folder and try this
InputStream raw = getApplicationContext().getAssets().open("simple.xml");
and try this
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder= dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(raw);
....
...
put you XML file in assets folder and Try this way
String xml;
Document doc;
try{
xml=getXML(getAssets().open("yourxmlfilename.xml"));
}catch(Exception e){
Log.d("Error",e.toString());
}
doc = XMLfromString(xml);
where getXML and XMLfromString method are as shown below
//getXML method
public static String getXML(InputStream is)throws IOException {
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
byte b = (byte)result;
buf.write(b);
result = bis.read();
}
return buf.toString();
}
//XMLfromString method
public final static Document XMLfromString(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) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
please use below code for parse local xml,
InputStream in = this.getResources().openRawResource(R.raw.xmlfile);
And then parse inputstream,
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();
DocumentBuilder db = dbf.newDocumentBuilder ();
Document document = db.parse(in, null);
Related
I have xml:
<Info>
<info_1/>
<info_2/>
<info_3>
<i ID="1"/>
<i ID="2"/>
<i ID="3"/>
</info_3>
<info_4>
</indo_4>
</Info>
I need to delete a specific node in info_3, for example a node in which ID = 1, how can I do this?
I tried to do this, but log shows before and after length = 3 :
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(bb)));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("i");
Log.e("LOG", "nList.getLength() = " + nList.getLength());
Node node=nList.item(1);
node.getParentNode().removeChild(node);
Log.e("LOG", "nList.getLength() = " + nList.getLength());
Solution that helped me:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(bb)));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("i");
Log.e("LOG", "nList.getLength() = " + nList.getLength());
Set<Element> targetElements = new HashSet<>();
for (int i = 0; i < nList_Loan_guarantor.getLength(); i++) {
Element e = (Element)nList_Loan_guarantor.item(i);
if ("10938".equals(e.getAttribute("ID"))) {
targetElements.add(e);
}
}
for (Element e: targetElements) {
e.getParentNode().removeChild(e);
}
doc.getDocumentElement().normalize();
NodeList nList_2 = doc.getElementsByTagName("i");
Log.e("LOG", "nList.getLength() = " + nList.getLength());
I am trying to parse an xml but it is returning all the chld nodes that have tag "nature".But I just want to only those nodes whose cat is selcted.
My xml looks like :-
<NatureList>
<NatureCategory cat="Crimes Against People">
<Nature>
<Name>Aggravated Assault</Name>
</Nature>
<Nature>
<Name>Annoyance Phone Calls</Name>
</Nature>
<NatureCategory>
<NatureCategory ...NatureCategory>
and parsing is done like this :
Document doc = XmlParser.getDomElement(xml);
NodeList n = doc.getElementsByTagName("NatureCategory");
try {
for(int i=0; i<n.getLength();i++)
{
Element e = (Element) n.item(i);
if(e.getAttribute("cat").equals(spinn.getSelectedItem().toString()))
{
Log.i("sub1", spinn.getSelectedItem().toString() );
NodeList n1 = doc.getElementsByTagName("Nature");
for(int j=0; j<n1.getLength();j++)
{
Element e1 = (Element) n1.item(j);
subcategory.add(getValue(e1, "Name"));
}
}
// subcategory.add()
}
}
nodes1 = doc.getElementsByTagName("NatureList");
for (int i = 0; i < nodes1.getLength(); i++) {
ObjectClass cgro = new ObjectClass();
Element e = (Element)nodes1.item(i);
cgro.NatureCategory = XMLfunctions.getValue(e, "NatureCategory");//here u can compare with your spinner string if match then parse this NatureCategory or save oe any logic which u like
nodes1a = doc.getElementsByTagName("cat");
for(int j = 0; j < nodes1a.getLength(); j++ ){
ObjectClass1 cgro1 = new ObjectClass1();
Element e2= (Element) nodes1a.item(j);
cgro1.cat= XMLfunctions.getCharacterDataFromElement(e2);
ArrayListClass.ItemList1.add(cgro1);
}
ArrayListClass.ItemList2.add(cgro);
}
and class use for this
public class XMLfunctions {
public final static Document XMLfromString(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) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
/** Returns element value
* #param elem element (it is XML tag)
* #return Element value otherwise empty String
*/
I think if form your XML like this it would be better:
<NatureList>
<NatureCategory>
<cat>Crimes Against People</cat>
<Nature>
<Name>Aggravated Assault</Name>
</Nature>
<Nature>
<Name>Annoyance Phone Calls</Name>
</Nature>
<NatureCategory>
Then get the cat tag and then test it.
I want to parse "ALışVERIş" type of content from service.
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
myXMLHandler = new XMLHandler();
xr.setContentHandler(myXMLHandler);
URL _url = new URL(params[0]);
xr.parse(new InputSource(_url.openStream()));
What I tried DOM Parser instead of XaxParser. Check below function and call it inside background thread :
public String readXML(){
StringBuilder stringBuilder = new StringBuilder();
try {
URL _url = new URL("http://182.160.161.2/~siva/turkish/web_serv/category.php?order_by=desc&category_id=2");
File fXmlFile = new File(new InputSource(_url.openStream()).getByteStream().toString());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(_url.openStream()).getByteStream());
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("document");
Node nResp = nList.item(0);
Element fstElmnt = (Element) nResp;
NodeList nameList1 = fstElmnt.getElementsByTagName("response");
Node mCat = nameList1.item(0);
Element catElmt = (Element) mCat;
NodeList catList = catElmt.getElementsByTagName("category");
System.out.println("----------------------------");
for (int temp = 0; temp < catList.getLength(); temp++) {
Node nNode = catList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
stringBuilder.append("Category ID : " + eElement.getElementsByTagName("category_name").item(0).getTextContent()+"\n");
stringBuilder.append("Category Name : " + eElement.getElementsByTagName("category_id").item(0).getTextContent());
System.out.println("Category ID : " + eElement.getElementsByTagName("category_name").item(0).getTextContent());
System.out.println("Category Name : " + eElement.getElementsByTagName("category_id").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
Here is a screenshot of my device, Have a look :
You can see those turkish language too :)
I have a XML file like this:
<?xml version="1.0"?>
<settings>
<mail id="sender">
<host>content here</host>
<port>25</port>
<account>tmt#example.com</account>
<password>password</password>
</mail>
<mail id="receiver">
<account>tmt#example.com</account>
</mail>
<mail id="support">
<account>tmt#example.com</account>
</mail>
</settings>
How can I get the attribute of each element, parse the content of each element and save the content in SharedPreference
This is what I've done so far:
The Contructor:
public ReadConfig(Context context, ProgressBar progressBar) throws ParserConfigurationException, SAXException, IOException {
this.context = context;
this.progressBar = progressBar;
folders = new CreateApplicationFolder();
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(new File(folders.getPathToNode() + "/settings_config.xml"));
doc.getDocumentElement().normalize();
}
And my doInBackground method
#Override
protected String doInBackground(String... params) {
Log.i("ROOT NODE: ", doc.getDocumentElement().getNodeName());
NodeList listOfMail = doc.getElementsByTagName("mail");
int totalMail = listOfMail.getLength();
Log.i("LENGTH: ", Integer.toString(totalMail));
for(int i = 0; i < totalMail; i++) {
Node firstMailSetting = listOfMail.item(i);
}
}
From the LogCat I know that there are three elements, which is correct.
import org.w3c.dom.Element;
for(int i = 0; i < totalMail; i++) {
Node firstMailSetting = listOfMail.item(i);
Element e = (Element) firstMailSetting ;
String acc = getTagValue("account", e); <-----
}
private String getTagValue(String sTag, Element eElement) {
try {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
catch (Exception e) {
return "";
}
}
Here is my code. I want to see these parsed strings into ListView in Android. How can I do this?
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("employee");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("name");
Element line = (Element) name.item(0);
System.out.println("Name: " + getCharacterDataFromElement(line));
NodeList title = element.getElementsByTagName("title");
line = (Element) title.item(0);
System.out.println("Title: " + getCharacterDataFromElement(line));
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}