Using only code Java I can get the root name with these lines.
Element root = document.getDocumentElement();
and get the name with root.getNodeName()
But in a Android enviroment, how can I get for example, the name 'aluno' as root name?
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body>
<ns1:autenticaAlunoResponse xmlns:ns1="http://xfire.codehaus.org/AlunoService">
<aluno xmlns="urn:bean.wsi.br">
<matricula xmlns="http://bean.wsi.br">61203475</matricula>
<turma xmlns="http://bean.wsi.br"><codigo>2547</codigo>
<nome>B</nome>
</turma>
</aluno>
</ns1:autenticaAlunoResponse>
</soap:Body>
</soap:Envelope>
Update (copied from a comment below):
I'm using Ksoap2 and trying to parse using SAX.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document doc = db.parse(is);
In your example 'aluno' appears as a tag name. If you work with Jsoup you can find the element by tag and then use tagName method to retrieve its name:
Document doc;
Elements tagName;
String name;
try {
doc = Jsoup.connect(url).userAgent("Mozilla").get();
} catch (IOException ioe) {
ioe.printStackTrace();
}
doc.select("aluno");
name = tagName.tagName();
Related
Ok, so I got some url link like https://stackoverflow.com/ and I'm trying to parse it in document but getting error. Why? Because this is not xml file, so the question is how can I get data as xml if i got only url?
My code:
public class URLReader {
public static void main(String[] args) throws Exception {
// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL("https://stackoverflow.com/").openStream());
int nodes = doc.getChildNodes().getLength();
System.out.println(nodes + " nodes found");
}
}
To parse HTML you may use JSOUP: https://jsoup.org/
This library provides also some features to transform HTML to XHTML, which some sort of XML:
Document document = Jsoup.parse(html);
document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
document.outputSettings().escapeMode(org.jsoup.nodes.Entities.EscapeMode.xhtml);
String xhtml=document.html();
Having the filedrop already implemented in my code, I need to parse the xml file I drop in the main().
Main()
case "XML":
text.append("Processing file type XML: "+files[i].getCanonicalPath() + "\n" );
ReadXml read_xml = new ReadXml();
read_xml.read(files[i].getCanonicalPath(), text);
break;
ReadXml.java
public class ReadXml {
ProgramDocument programDocument = new ProgramDocument();
public void read(String FILE, javax.swing.JTextArea text ) {
try {
JAXBContext context = JAXBContext.newInstance(ProgramDocument.class);
Unmarshaller u = context.createUnmarshaller();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(FILE);
Object o = u.unmarshal( doc );
doc.getDocumentElement().normalize();
text.append("Account : " +doc.getElementsByTagName("Account").item(0));
}
catch(Exception e) {
text.append("XML file not parsed correctly.\n");
}
}
}
I am not able to print anything, and when I am, I see "NULL" or just empty row or some path#numbers
I am not a developer, I just need to try opening a xml a send contents to a DB, but this is too far already.
EDIT: added part of xml
<?xml version="1.0" encoding="UTF-8"?>
<ARRCD Version="48885" Release="38">
<Identification v="ORCOZIO"/>
<Version v="013"/>
<Account v="OCTO">
<Type v="MAJO"/>
<Date v="2016-05-14"/>
</AARCD>
There are no elements tagged "Account" in the element "Account".
What you want to read here are the Attributes of Account, not other elements.
Thus you should use eElement.getAttribute("v") if you want to read attribute v, not getElementsByTagName()
I am trying to parse an XML and then insert it an Excel File.
If I run my code it works even with errors but I cannot make any modification to it because I still got errors. Here is my code:
public class Parsing {
private void parseXmlFile(){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//using Factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation
dom = db.parse("Employee.xml"); }
} catch )
}
}
What is wrong with this?
Can someone help me? I've been searching all over google and it's eating my nerves.
it should be like this :-
private void parseXmlFile(){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//using Factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation
Document dom = db.parse("Employee.xml");
} catch(IOException ex ){ // OR Any Specific Exception should be catched here
// your error handling code here
}
}
Also Employee.xml should be in the current directory or give complete abosulte path of Employee.xml file also.
I want to unmarshall a element into a Class Property, which Type is Object, as to keep it generic.
I tried to build the class and marshall into xml, unmarshall it back,the result was fine.
But when i try to do this with an normal generated Xml-Document(although it has the same structure), the value of the result Class Object Property is null.
Here is my Teststructure:
#XmlRootElement
public class TestStructure {
private Object test;
public Object getTest() {
return test;
}
public void setTest(Object test) {
this.test = test;
}
}
I try to marshall this, and get this xml-document:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testStructure>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">foo</test>
</testStructure>
However, if i try to arbitrarly build this structure Via Domsource to get the same Xml document:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root element
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("testStructure");
doc.appendChild(rootElement);
Element test = doc.createElement("test");
test.appendChild(doc.createTextNode("foo"));
test.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
test.setAttribute("xsi:type", "xs:string");
test.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
rootElement.appendChild(test);
and Unmarshal the document:
JAXBContext context2 = JAXBContext.newInstance(TestStructure.class);
Unmarshaller m2 = context2.createUnmarshaller();
TestStructure testobject2 =
( TestStructure ) m2.unmarshal(doc);
System.out.println(testobject2.getTest());
The attribute appears to be "null".
So, what went wrong?
woah, thanks to W A , i got the solution :)
You just have to modify the Element Attributes:
Element test = doc.createElement("test");
test.appendChild(doc.createTextNode("foo"));
test.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:type", "xs:string");
test.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
After search on internet and in differnets forums, have not found my answer.
I have a XML file which is define by two XSD schema.
For write the XML file, there are two ways to write the XML file :
(I have to delete the "<" charactere to display the XML file)
First methode to write it :
?xml version="1.0" encoding="UTF-8" standalone="yes"?>
Policy xmlns="http://www.W3C.com/Policy/v3#" xmlns:ns2="http://www.W3C.com /PolicyExtension/v3#">
DigestAlg Algorithm="http://test"/>
Transforms>
Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n20010315"></Transform>
/Transforms>
ns2:Validation>
ns2:ConditionID>1.0.1</ns2:ConditionID>
ns2:TConditionID>1.0.2</ns2:TConditionID>
/ns2:Validation>
/Policy>"
second methodes :
?xml version="1.0" encoding="UTF-8" standalone="yes"?>
Policy xmlns="http://www.W3C.com/Policy/v3#">
DigestAlg Algorithm="http://test"/>
Transforms>
Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n20010315"></Transform>
/Transforms>
Validation xmlns:ns2="http://www.W3C.com/PolicyExtension/v3#">
ConditionID>1.0.1</ns2:ConditionID>
TConditionID>1.0.2</ns2:TConditionID>
/Validation>
/Policy>
For pasring my XML files, i use :
InputStream doc = new FileInputStream(myXMLFile);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
List<Source> sourceListSchema = new ArrayList<Source>();
sourceListSchema.add(new StreamSource(SignaturePolicy.class.getResourceAsStream(MY_XSD_SCHEMA_1)));
sourceListSchema.add(new StreamSource(SignaturePolicy.class.getResourceAsStream(MY_XSD_SCHEMA_2)));
Schema schema;
try {
Source[] sourceTmp = new Source[1];
schema = sf.newSchema(sourceListSchema.toArray(sourceTmp));
} catch (SAXException e) {
LogMachine.logger.severe(
"SAXException : The schema can not be parse :"+e.getMessage());
}
dbf.setIgnoringElementContentWhitespace(true);
dbf.setNamespaceAware(true);
dbf.setIgnoringComments(true);
dbf.setSchema(schema);
DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
documentPolicy = db.parse(Doc);
} catch (ParserConfigurationException e) {
LogMachine.logger.severe(
"ParserConfigurationException : the file can not be parse by DOM :"+e.getMessage());
} catch (SAXException e) {
LogMachine.logger.severe(
"SAXException : the file can not be parse by DOM :"+e.getMessage());
} catch (IOException e) {
LogMachine.logger.severe(
"IOException : the file can not be open like a file :"+e.getMessage());
}
When I want to parse this documents with DOM, the first XML file display an error
Exception in thread "main" org.w3c.dom.ls.LSException: The prefix "ns2" for element "ns2:Validation" is not bound.
But the second XML file is well parse.
Someone can help me to parse the two documents ??
Thank you for you help