I need create a dom document as this:
<namespace:Facturae xmlns:namespace="URI1" xmlns:namespace2="URI2">
//<.......
</namespace:Facturae>
But the following code produce the error:
NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
The code is:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element FacturaeElement = document.createElementNS("URI1", "Facturae");
document.appendChild(FacturaeElement);
FacturaeElement.setPrefix("namespace"); //First namespace OK
FacturaeElement.setAttributeNS("URI2", "xmlns:namespace2", "aaa"); //Generate error
//Rest of code
How I can put a second namespace into element??
Searching more information I have reached the solution:
I use the normal setAtribute method (without namespace) indicating the name of the atribute with the xmlns prefix so: "xmlns:namespace2".
Then, I create the sub element with this the namespace and later put the prefix.
Element FacturaeElement = document.createElementNS("URI1", "Facturae");
document.appendChild(FacturaeElement);
FacturaeElement.setPrefix("namespace"); //First namecpace
FacturaeElement.setAttribute("xmlns:namespace2", "URI2"); //second namespace
//I create the subelement with a namespace
Element FileHeaderElement = document.createElementNS("URI2", "FileHeader");
FacturaeElement.appendChild(FileHeaderElement);
FileHeaderElement.setPrefix("namespace2");
Related
I am Building XML Using JAVA,my element have few attribute and that attribute contains '-'
but when setting attibute as :
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element dffgr=doc.createElement("diffgr:diffgram");
dffgr.setAttribute("xmlns:msdata", "urn:schemas-microsoft-com:xml-msdata".toString());
dffgr.setAttribute("xmlns:diffgr", "urn:schemas-microsoft-com:xmldiffgram-v1".toString());
'-' is replaced by 'xAD'
as Output is :
<diffgr:diffgram xmlns:diffgr="urn:schemasέicrosoftΣom:xmlΤiffgramζ1" xmlns:msdata="urn:schemasέicrosoftΣom:xmlέsdata">
and desired output is :
<diffgr:diffgram xmlns:msdata="urn:schemasmicrosoftcom:xmlmsdata" xmlns:diffgr="urn:schemasmicrosoftcom:xmldiffgramv1">
Plese Help.
Copy and paste this:
dffgr.setAttribute("xmlns:msdata", "urn:schemas-microsoft-com:xml-msdata");
dffgr.setAttribute("xmlns:diffgr", "urn:schemas-microsoft-com:xmldiffgram-v1");
You are using the wrong character for -.
I'm using Dom Parser in Java to process a XML file. Is I have an Object of type Node,how can I find elements by name inside that Node? I know how to find by tag name from all the document, I have this:
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(this.file);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("SomeTag");
But then, inside every item of nList how I find by tagName?should I have to loop on it and make comparations?
EDITED:
The structure of the XML tree is as follows, there's a lot of agents:
</agent>
<agent name='agente2' id='ug4pht1ju6ru8u5aot37tcb5po'>
<AgentModel>
<Posicion></Posicion>
<MarcoReferencia></MarcoReferencia>
<AgenteDescripcion></AgenteDescripcion>
<Componentes>
</Componentes>
<Objetivo>
<Nombre></Nombre>
<Descripcion></Descripcion>
<Activacion></Activacion>
<Finalizacion></Finalizacion>
<Exito></Exito>
<Fracaso></Fracaso>
<Ontologia></Ontologia>
<Entradas>
</Entradas>
<Salidas>
</Salidas>
</Objetivo>
<Servicios>
</Servicios>
<Propiedades>
<Nombre></Nombre>
<Calidad></Calidad>
<Auditable></Auditable>
<Garantia></Garantia>
<Capacidad></Capacidad>
<Confiabilidad></Confiabilidad>
</Propiedades>
<Capacidad>
<Habilidades></Habilidades>
<Representacion></Representacion>
<Lenguaje></Lenguaje>
</Capacidad>
<Restriccion>
<Normas></Normas>
<Preferencias></Preferencias>
<Permisos></Permisos>
</Restriccion>
</AgentModel>
<CommunicationModel>
</CommunicationModel>
<CoordinationModel>
</CoordinationModel>
<MarcoOntologicoIndividual>
</MarcoOntologicoIndividual>
<Asociaciones>
</Asociaciones>
<Actores>
</Actores>
<CasosUso>
</CasosUso>
</agent>
So, in a NodeList a have all the agents, then, for each of them I want get the tags looking by name
I have the following xml snippet from which I am trying to retrieve the first element using JDOM but I am getting nullpointer exception.please help me out if any one knows.
<db1:customer xmlns:db1="http://www.project1.com/db1">
<db1:customerId>22</db1:customerId>
<db1:customerName>PRASAD44</db1:customerName>
<db1:address>Chennai</db1:address>
<db1:email>pkk#gmail.com</db1:email>
<db1:lastUpdate>2014-08-01T00:00:00+05:30</db1:lastUpdate>
<db1:nameDetail>BSM_RESTeter</db1:nameDetail>
<db1:phoneBiz>9916347942</db1:phoneBiz>
<db1:phoneHome>9916347942</db1:phoneHome>
<db1:phoneMobile>944990031</db1:phoneMobile>
<db1:rating>22</db1:rating>
</db1:customer>
here is what I am doing,
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("CommonFiles/file.xml");
Document doc = (Document) builder.build(xmlFile);
Element rootNode = doc.getRootElement();
Element customerid = rootNode.getChild("sure:customerId");
System.out.println("customerid ======"+customerid);
The print statement displays null.
When dealing with XML containing namespaces, you need to use the Namespace instance that's appropriate for your document. In this case, you have:
<db1:customer xmlns:db1="http://www.project1.com/db1">
The namespace here is http://www.project1.com/db1 and the prefix is db1.
In JDOM you can creaate a reference to a namespace with:
Namespace db1 = Namespace.getNamespace("db1", "http://www.project1.com/db1");
Now, when you retrieve the content in your document, use:
Element customerid = rootNode.getChild("customerId", db1);
Note that you get content using the Namespace object, not the prefix for the element (there is no "db1:" prefix for the "customerId"
I'm trying to send a SOAP message.
I'm adding manually header to the message, using the next code:
public static void main(String[] args) {
try{
AmdocsServicesServiceagentLocator locator = new AmdocsServicesServiceagentLocator();
PortTypeEndpoint1BindingStub port = new PortTypeEndpoint1BindingStub(new URL("http://srvp7rd-tibco.rnd.local:8025/Process/SoapRequests/Amdocs-Services.serviceagent/PortTypeEndpoint1"),locator);
GetContactRelatedInfo parameters = new GetContactRelatedInfo();
GetContactRelatedInfoRequest request = new GetContactRelatedInfoRequest();
request.setPersonID("6610782925");
request.setPersonIDType("ID number (CPR)");
/* Creating an empty XML Document - We need a document*/
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
/* Creating the XML tree */
/* Create the root element and add it to the document */
Element root = doc.createElement("mul:MultiTenant");
doc.appendChild(root);
/* Adding the child to the root */
Element child = doc.createElement("mul:OpCo");
root.appendChild(child);
/* Add text element to the child */
Text text = doc.createTextNode("DENMARK");
child.appendChild(text);
/* Adding the child to the root */
child = doc.createElement("mul:BS");
root.appendChild(child);
/* Add text element to the child */
text = doc.createTextNode("ENV3");
child.appendChild(text);
SOAPHeaderElement element = new SOAPHeaderElement("" ,"soapenv:Header" , doc);
element.setActor(null);
port.setHeader(element);
System.out.println(port.getHeaders()[0]);
port.getContactRelatedInfoOperation(parameters);
} catch (Exception e){
e.printStackTrace();
}
}
But I don't know why, or how I'm ending up with a message including attributes that i didn't wanted.
For example the output message of the current code is:
<soapenv:Header soapenv:mustUnderstand="0" xsi:type="ns1:Document"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ns1="http://xml.apache.org/xml-soap">
<mul:MultiTenant xmlns:mul="">
<mul:OpCo xmlns:mul="">DENMARK</mul:OpCo>
<mul:BS xmlns:mul="">ENV3</mul:BS>
</mul:MultiTenant></soapenv:Header>
For example, the xmlns:mul="" attribute in the mul:OpCo tag.
Is there a way to delete that attribute?
Those aren't attributes, those are namespace declarations. You're creating elements with the mul: namespace prefix, and that prefix has to be defined somewhere. Java is adding a default empty declaration (xmlns:mul="") just so that your XML ends up being well-formed - you can't use a prefix without declaring it.
If you don't want those declarations, then remove the mul: prefix, or define it properly elsewhere in the document. You haven't told us what your document should look like, though, so it's hard to advise you how to do that.
You message doesn't have a declaration of the mul namespace. Add it, and the strange xmlns:mul attributes should go away.
Update
Now I understand, you just create a fragment of a soap message. This is just the header and the mul namespace may be declared on the other SOAP-Envelope element.
You need to know the namespace(-name) of mul, double check the full SOAP message in soapUI and double-check the documentation. Then declare the namespace on doc. Later, if the outer element declares mul exactly the same way, the attributes should disappear from the serialized xml.
I am trying to get an attribute of an xml node example:
<Car name="Test">
</Car>
I want to grab the name attribute of the car node.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(configFile);
doc.getDocumentElement().normalize();
NodeList layerConfigList = doc.getElementsByTagName("CAR");
Node node = layerConfigList.item(0);
// get the name attribute out of the node.
this is where i get stuck because the only method that looks like i can use is getAttributes() with returns a NamedNodeMap and im not sure how to extract it from that.
Your node is an Element so you just have to
Element e = (Element)node;
String name = e.getAttribute("name");
you can do it without using elements, like this:
//HtmlTag represents any arbitrary node that you are trying to get its "car" attribute
if("HtmlTag".equals(node.getNodeName()))
String nodeContent=node.getAttributes().getNamedItem("car").getNodeValue()