Inserting elements in xml - java

I am trying to add elements to xml. I followed Java DOM - Inserting an element, after another
but that did not work for me. Here is my code:
Element e = dom.createElement("mapping");
e.setAttribute("resource", "/some/path/to/file");
Element lastChild = (Element)nList.item(nList.getLength()-1);
Element parent= (Element)nList.item(nList.getLength()-1).getParentNode();
lastChild.getParentNode().insertBefore(e, lastChild);
I also tried parent.appendChild(e); but none of them work. It doesn't seem like there is problem with the code. What could be the problem?
I am using Netbeans on macosx. Is this because of file permissions ?

The Elements you are working with are a DOM in memory, they are not directly tired to your file contents. The code snippet you posted only modifies that DOM. You will only see change in the file if you write your data back to the file.

Related

How can I get the LineNumber of the element when using Jsoup?

such as:
Document doc = Jsoup.parse(file,"UTF-8");
Elements eles = doc.getElementsByTag("style");
How can I get the lineNumber of eles[0] in the file?
There is no way for you to do it with Jsoup API. I have checked on their source code: org.jsoup.parser.Parser maintains no position information of the element in the original input.
Please, refer to sources on Grep Code
Provided that Jsoup is build for extracting and manipulating data I don't believe that they will have such feature in future as it is ambigous what element position is after manipulation and costly to maintain actual references.
There is no direct way. But there is an indirect way.
Once you find the point of interest like an attribute, simply add a token as html before the element, and write the file to another temporary file. The next step is do a search for the token, using text editing tools.
code is as follows.
Step-1:
// get an element
for (Element element : doc.getAllElements()) {
... some code to get attributes of element ...
String myAttr = attribute.getKey();
if (myAttr.equals("some-attribute-name-of-interest") {
System.out.println(attribute.getKey() + "::" + attribute.getValue());
element.before("<!-- My Special Token : ABCDEFG -->");
}
Step-2:
// write the doc back to a temporary file
// see: How to save a jsoup document as text file
Step-3:
The last step is search for "My Special Token : ABCDEFG" in the output file using a text editing tool.
jsoup is a nice library. I thought this would help others.

How can I use XPath to create a new xml content?

I have the following problem. Into a Java application I have to create a new XML content using XPath (I always used it to parse XML files and obtain values inside its tag, can I use it also for build a new XML content?).
So my final result (that have to be saved on a database CLOB field, not on an .xml file, but I think that this is not important) have to be something like this:
<?xml version="1.0" encoding="ISO-8859-1"?>
<Messaggio>
<Intestazione>
<Da>06655971007</Da>
<A>01392380547</A>
<id>69934</id>
<idEnel/>
<DataInvio>2015-05-06</DataInvio>
<DataRicezione/>
<InRisposta/>
<TipoDoc>Ricevuta</TipoDoc>
</Intestazione>
<Documenti>
<Ricevuta>
<Testata>
<Documento>
<Tipo>380</Tipo>
<NumeroDocumento>ff</NumeroDocumento>
<Stato>KO</Stato>
<Data>2014-03-10</Data>
</Documento>
</Testata>
<Dettaglio>
<Messaggio>
<Codice>000</Codice>
<Descrizione>Documento NON Conforme / NON dovuto</Descrizione>
</Messaggio>
</Dettaglio>
</Ricevuta>
</Documenti>
</Messaggio>
So what I need to do is to programmatically add the nodes and the content of these nodes (the content is obtained from a model object).
Can I do it using XPath? How?
Tnx
XPath is an API to locate nodes in a XML document. It can't create new nodes or manipulate existing nodes. So what you need is to locate the nodes to modify using XPath and then use the API of the found nodes to make the changes.
But in your case, you're starting with an empty document. Have a look at frameworks like JDOM 2 to build XML documents from scratch. This tutorial should get you started: http://www.studytrails.com/java/xml/jdom2/java-xml-jdom2-example-usage.jsp
You can't. XPath is a matching technology, not a content creation technology. Possibly you are looking for XSLT?

Validate XML - remove invalid data

I want to validate an xml file against it schema. Once the validation is completed I want to remove any invalid data and save this invalid data into a new file. I can perfom the validation, just stuck on the removing and saving invalid data into new file.
I take back everything I just wrote. ... :) You can get the node you need using the Current Element Node property at Exception time, it seems.
Element curElement = (Element)validator.getProperty("http://apache.org/xml/properties/dom/current-element-node");
Because the Schema is defined via Xerces, I think this will work. See http://xerces.apache.org/xerces2-j/properties.html#dom.current-element-node .
There is more explanation in the answer at How can I get more information on an invalid DOM element through the Validator? .

Get an XML from a url using dom

I have store in a String variable(link) the url that I get the xml response, I use a dom to parse the xml data.
In order to be sure that I extract the data correctly I store the xml in the local drive, build my parser and I took the data:
document = builder.parse(new File(filepath));
So when I try to get it from url I used:
document = builder.parse(new URL(link).openStream());
And it didn't work. What am I missing?
The data of the xml are stored in a list which then are shown in a jsf datatable.
Well the above works just fine, the problem was the index of elements of the nodelist. For some reason when i was reading from file
obj.setattribute1(cDetails.item(1).getTextContent());
obj.setattribute2(cDetails.item(3).getTextContent());
see that the item are increased by 2 each time
now that i read a URL the increment is 1 every time
Now i am sure that there is a reason for this which i don't understand probably cause of my limited yet knowledge but the above work and the index of the item increases 1 for the next item in the nodelist.

Copy a whole ODT (Openoffice Writer) document section to other document with Openoffice Java API (UNO API)

I need to use the OpenOffice Java API to copy a document section and paste it over another document section. So far I have managed to copy the text of the section of the source document and paste it over the section at the target document (see the example below).
However, the problem is that non-text elements (graphics, formats, tables, etc.) don't get pasted on the destination document.
The code I have used to extract the text of the source section is:
// Read source file text
XComponent xComponentSource = this.ooHelper.loadDocument("file://" + fSource);
// Get sections
XTextSectionsSupplier textSectionsSupplierSource = (XTextSectionsSupplier)UnoRuntime.queryInterface(XTextSectionsSupplier.class, xComponentSource);
XNameAccess nameAccessSource = textSectionsSupplierOrigen.getTextSections();
// Get sections by name
XTextSection textSectionSource = (XTextSection)UnoRuntime.queryInterface(XTextSection.class, nameAccessOrigen.getByName("SeccEditable"));
//Get section text
String sectionSource = textSectionSource.getAnchor().getString();
To paste the text over the target section, the code to select the section is the same, and I set the string:
textSectionDest.getAnchor().setString(sectionSource);
I have read the API Javadoc, and I haven't found any method to copy the entire section. Is there any way to do it?
I was having this same problem. I ended up solving by creating two cursors, one at the start of the content of what I wanted duplicated, then another at the end of the content by using, then extending the cursor selection of the first one to the second. This used the gotoRange method on the first cursor, passing in the second cursor and a True to tell it to expand selection.
Cursor Example:
http://api.openoffice.org/docs/DevelopersGuide/Text/Text.xhtml#1_3_1_1_Editing_Text
Then I created an autoText container, group and element containing the selection. and inserted /pasted the content at a cursor position using the applyTo method of the autotext entry. I used a guid for the name of the autoText container so it would be unique and then deleted the container when I was done.
AutoText Example:
http://api.openoffice.org/docs/DevelopersGuide/Text/Text.xhtml#1_3_1_6_Auto_Text
I can post my code if you want, however it's written in Python.

Categories

Resources