I am creating an XML file using Java.
I created root node using createElemenNS() to createh root node with namespace.
Element root = doc.createElementNS("http://www.myorc.com/schemas", "InvConf");
Then I created a node using createElement() and added it to root node. This node is automatically added with namespace like below.
Element invList = doc.createElement("InvList");
root.appendChild(invList);
<InvConf xmlns="http://www.myorc.com/schemas">
<InvList xmlns="">
...
</InvList>
<InvList xmlns="">
...
</InvList>
<InvList xmlns="">
...
</InvList>
</InvConf>
How to avoid adding the namespace to child nodes ?
I want the final XML to be like the following
<InvConf xmlns="http://www.myorc.com/schemas">
<InvList>
...
</InvList>
<InvList>
...
</InvList>
<InvList>
...
</InvList>
</InvConf>
Found that issues is coming only when xmlparserv2.jar is in CLASSPATH. This is required by some parts for the application. How to resolve this ?
The xmlns="" were added because your child is not in a namespace, and your parent is. To change that, put it in the namespace at the time you create the element.
Change the
createElement("InvList");
To the correct namespace.
As pointed out in comments xmlns="" means that element doesn't have any namespace. E.g. from XML parser point of view following two documents are identical:
<ns:root xmlns:ns="http://namespace.com">
<child/>
</ns:root>
and
<root xmlns="http://namespace.com">
<child xmlns=""/>
</root>
To avoid creation of xmlns="" in elements not belonging to any namespace you can create prefix on upper level element:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element root = doc.createElementNS("http://namespace.com", "root");
root.setPrefix("ns");
Element child = doc.createElementNS("", "child");
root.appendChild(child);
doc.appendChild(root);
This code will create following XML:
<ns:root xmlns:ns="http://namespace.com">
<child/>
</ns:root>
Alternatively you can use following syntax to achieve same result:
Document doc = db.newDocument();
Element root = doc.createElementNS("http://namespace.com", "ns:root");
Element child = doc.createElementNS("", "child");
root.appendChild(child);
doc.appendChild(root);
When commenting out line root.setPrefix("ns"); or creating element without prefix (doc.createElementNS("http://namespace.com", "root");) following XML will be generated:
<root xmlns="http://namespace.com">
<child xmlns=""/>
</root>
Related
I need to create an .xml file but compiller says to me:
No such namespace prefix
I want to get:
<root>
<header>
<etd:name>test</etd:name>
</header>
</root>
My code:
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root", getXmlNamespace()).addAttribute(new QName("xmlns:etd"), "some-url-there");
Element header = root.addElement("header");
header.addElement("etd:name").addText("test");
I've tried with addElement(new QName("etd:name")) but that shows me empty value xmlns="" which i dont want.
I am creating a xml request using java.
I am new in creating xmls using java.
Here is code:
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("UserRequest");
rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ns0", "https://com.user.req");
rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
doc.appendChild(rootElement);
// user element
Element user = doc.createElement("User");
rootElement.appendChild(user);
// userAttributes element
Element userAttr = doc.createElement("UserAttributes");
rootElement.appendChild(userAttr);
// name elements
Element name = doc.createElement("Name");
name.appendChild(doc.createTextNode("hello"));
userAttr.appendChild(name);
// value elements
Element value = doc.createElement("Value");
name.appendChild(doc.createTextNode("dude"));
userAttr.appendChild(value);
Expected output:
<?xml version="1.0" encoding="UTF-8"?>
<UserRequest
xmlns:ns0="https://com.user.req"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:type="ns0:UserRequest">
<User/>
<UserAttributes>
<Name>hello</Name>
<Value>dude</Value>
</UserAttributes>
</UserRequest>
Generated output:
<?xml version="1.0" encoding="UTF-8"?>
<UserRequest
xmlns:ns0="https://com.user.req"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<User/>
<UserAttributes>
<Name>hello</Name>
<Value>dude</Value>
</UserAttributes>
</UserRequest>
How to get correct namespace (as shown at expected section).
There's nothing wrong with the namespaces in your generated output. However this is an accident ... you're using setAttributeNS() to do something it's not intended for.
Read up on XML namespace declarations and namespace prefixes. That will be a lot easier than trying to explain point-by-point why you're not getting what you expected. For example, xmlns is not a namespace prefix, and xsi:type is not a namespace.
Instead of trying to create the desired namespace declarations as if they were normal attributes, delete these two lines
rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/",
"xmlns:ns0", "https://com.user.req");
rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/",
"xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
and instead use
rootElement.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
"xsi:type", "ns0:UserRequest");
This should give you most of your expected output, except for the ns0 namespace prefix declaration. It won't generate that because you're not using ns0 on any element or attribute. Did you mean to have
<ns0:UserRequest ...
in your expected output?
I try to add new <class> elements to a persistence.xml file with JDOM2.
persistenceUnitEl.add(new Element("class").addContent(className));
The problem is that jdom2 always adds xmlns="" to the <class> elements.
How can i prevent this?
removeAttribute("xmlns") does not work and removeNameSpace(el.getNameSpace()) also does not work.
JDOM only adds the xmlns="" if you add child elements to other elements that are already in a namespace. The default Namespace in XML is the one which has no prefix. In the following example:
<root>
<child />
</root>
There are no namespace prefixes, and the default namespace is "".
The above XML snippet is semantically identical to:
<root xmlns="" >
<child />
</root>
The xmlns="" means that, any time you see an element that has no prefix, that you should put it in the 'empty' namespace "".
Now, if you want to put things in a namespace, and have a prefix, you would do:
<ns:root xmlns:ns="http://mynamespace">
<ns:child />
</ns:root>
Note that the root and child elements in the above example are in the namespace http://mynamespace, and that namespace has the prefix ns. The above code would be semantically identical to (has the same meaning as):
<root xmlns="http://mynamespace">
<child />
</root>
In the above example, the default namespace is changed from "" to be http://mynamespace, so now elements that have no prefix are in that default namespace http://mynamespace. To reiterate, the following two documents are identical:
<ns:root xmlns:ns="http://mynamespace">
<ns:child />
</ns:root>
and
<root xmlns="http://mynamespace">
<child />
</root>
Now, what does all of this have to do with your problem?
Well, your element persistenceUnitEl must be in a default namespace that is not "". Somewhere on that element, or on of it's parents, you have something like:
<tagname xmlns="...something....">
<PersistenceUnit>
</PersistenceUnit>
</tagname>
In the above, the PersistenceUnit is in the namespace ...something..... Now, you are asking JDOM to add the element new Element("class") to the document, so you are getting:
<tagname xmlns="...something....">
<PersistenceUnit>
<class xmlns="" />
</PersistenceUnit>
</tagname>
The reason is because you are telling JDOM to put it in the "" namespace (Namespace.NO_NAMESPACE). See the documentation for JDOM here: new Element(String name).
instead, what you want to do, is put it in the same namespace as the parent:
Namespace parentNamespace = persistenceUnitEl.getNamespace();
persistenceUnitEl.add(new Element("class", parentNamespace).addContent(className));
Now, the real question is whether the "class" element actually belongs in the same namespace as the parent, or not. But that is a question only you can answer.
Resources:
Namespace specification
Decent introduction
A tutorial (quite advanced)
JDOM's NamespaceAware documentation
JDOM's FAQ
From my understanding, I think this is what you want.
<RootTagname xmlns="...some namespace....">
<SubTag>
<NewElement yourAttrib="1"/>
</SubTag>
</RootTagname >
This is what you get.
<RootTagname xmlns="...some namespace....">
<SubTag>
<NewElement xmlns="" yourAttrib="1"/>
</SubTag>
</RootTagname >
Use the below snippet to create the new Element
Element newElement = new Element("NewElement", subElement.getNamespace());
Here is the full code.
Namespace namespace = Namespace.getNamespace("prefix", ".....some namespace....");
XPathBuilder<Element> subTagXpathelementBuilder = new XPathBuilder<Element>("//prefix:SubTag", Filters.element());
subTagXpathelementBuilder.setNamespace(namespace);
XPathFactory xpathFactory = XPathFactory.instance();
Document doc = (Document) builder.build(xmlFile);
XPathExpression<Element> xpath = subTagXpathelementBuilder .compileWith(xpathFactory);
List<Element> subElementsList = xpath.evaluate(doc);
for (Element subElement : subElementsList ) {
Element newElement = new Element("NewElement", subElement.getNamespace());
List<Attribute> newElementAttribList = newElement.getAttributes();
newElementAttribList .add(new Attribute("yourAttrib", "1"));
subElement .addContent(newElement);
}
I have a basic XML document setup like this:
<rss>
<channel>
</channel>
</rss>
I would like to add new child nodes of the channel as the first node, so, say I'm looping through a collection of items, then the first item would be added like this:
<rss>
<channel>
<item>Item 1</item>
</channel>
</rss>
Then the next item would added like this:
<rss>
<channel>
<item>Item 2</item>
<item>Item 1</item>
</channel>
</rss>
I've been trying to use:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(xmlFile));
Element itemNode = doc.createElement("item");
Node channelNode = doc.getElementsByTagName("channel").item(0);
channelNode.appendChild(itemNode);
But it keeps adding new items to the bottom of the list.
channelNode.appendChild(itemNode);
will always append the itemNode to the end of the list of children of channelNode. This is behavior is defined in the DOM Level 3 specification, and in the JAXP documentation as well:
Node appendChild(Node newChild)
throws DOMException
Adds the node newChild to the end of the list of children of this
node (emphasis mine). If the newChild is already in the tree, it is first removed.
If you need to add at the beginning of the list of child nodes, you can use the insertBefore() API method instead:
channelNode.insertBefore(itemNode, channelNode.getFirstChild());
Im in the process of creating XML as a Node for a RMI program I am developing but I have run across a problem. I can create the XML using DOM but I am struggling to add namespace and version to the top of my XML. I have tried using setAttribute and setAttributeNS but at the moment lost in what else I can do.
The java code to create the element is:
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Node root = doc.createElement("Request");
doc.appendChild(root);
//code ommited
The result I get currently is:
<Request>
<Identification>
<UserID>user</UserID>
<Password>pass</Password>
</Identification>
</Request>
In the request section I need it to look like:
<Request xsi:noNamespaceSchemaLocation="URL" Version="1.0">
Any help will be appreciated to help solve this issue!
Thanks
I think you'd want something like:
...
Element root = doc.createElement("Request");
root.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:noNamespaceSchemaLocation", "URL");
root.setAttribute("Version", "1.0");
doc.appendChild(root);
...
Defining root as an Element gives you the .setAttribute* methods.
This would give you
<Request Version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="URL"/>
I know that includes a bit more, but the xmlns:xsi attribute is needed so that the xsi namespace is defined.