I am trying to evaluate XPath Expression "/feed/entry/title" using:
NodeList nodeList = (NodeList) inputXMLxpath.evaluate("/feed/entry/title", xmlDoc,
XPathConstants.NODESET);
If the xmlDoc is like this:
<?xml version="1.0" encoding="UTF-8"?>
<feed>
<entry>...
<feed>
I get proper results, but when xmlDoc is like this:
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-US">
<entry>...
</feed>
the result of XPath evaluation is always an empty list.
Can anybody tell the reason for this and suggest a solution such that I get proper result in second case also?
The xmlns-"...." is a namespace declaration, and it has the effect of changing the names of the elements in the document so that they are no longer called "feed" and "entry", but something more complicated. Google for "XPath default namespace declaration".
Related
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?
The following is a sample of what my xml sheet looks like and as you can see there is a possibility that there can be multiple genres, actors, directors, and companies. How would I specifically access each one.
Preferably answer this question with XPath and Java but if you don't know those and have an answer then tell me what you know.
<?xml version="1.0" encoding="UTF-8"?>
<movies>
<movie>
<title>Seven</title>
<actor>Pitt</actor>
<director>Fincher</director>
<genre>action</genre>
<genre>drama</genre>
<year>1995</year>
<company>Cecchi_Gori_Pictures</company>
<grading>79</grading>
</movie>
</movies>
//read a nodelist using xpath
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
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);
}
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.
I'm reading an existing XML file and outputting it (using DOM).
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="test"?>
<Books>
<Book name="MyBook" />
</Books>
But how do I modify the XML stylesheet? -> href here set "test".
Something like this should work (untested)
Element root = doc.getDocumentElement();
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/processing-instruction('xml-stylesheet')";
ProcessingInstruction pi;
pi = (ProcessingInstruction)xpath.evaluate(expression, doc, XPathConstants.NODE);
pi.setData("type='text/xsl' href='foo.xsl'");
Thats a bit tricky, but why not read the file first into a String and do a replace before sending it via a stream into the dom parser.