0

I need to split one big XML into many child.xml files. I my code works except for a change value. I need to insert my String Titleproper Bla bla text <num>X</num> in a existing element titleproper.

I tried:

header.getElementsByTagName("titleproper").item(0).setTextContent(Titleproper);

but my result is:

<titleproper> Bla bla text lt;num;gt;1lt;/numgt;</titleproper>

I understand why, but I don't know how to cheat this restriction. I need to insert Text+Xml code in my titleproper.

Pegazuss
  • 11
  • 5

1 Answers1

-1

If the Titleproper string is XML itself then you need to parse this XML and insert the resulting nodes into the target tree. The org.w3c.dom.ls interfaces can help you here.

// we need to get the DOMImplementation from the Document - if header is an
// Element then do:
DOMImplementationLS ls =
    (DOMImplementationLS)header.getOwnerDocument().getImplementation();
// if header is already a Document then it's just
//DOMImplementationLS ls =
//    (DOMImplementationLS)header.getImplementation();

// LSInput represents the source from which the XML to be parsed will be taken
LSInput input = ls.createLSInput();
input.setStringData(Titleproper);

// LSParser does the parsing
LSParser parser = ls.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

// parseWithContext(input, context, action) parses the fragment given by input
// and inserts the results at a position relative to the node "context".  In this
// case we use ACTION_REPLACE_CHILDREN which means remove all the child nodes
// (if any) from the context node and replace them with the result of the parse.
// Alternative actions include replacing the context node entirely, inserting
// the parse results as siblings before or after the context node, etc.
parser.parseWithContext(input,
    header.getElementsByTagName("titleproper").item(0),
    LSParser.ACTION_REPLACE_CHILDREN);
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
  • i understand the explain, but not the Code. i try a copy/past test but the first line return me `java.lang.NullPointerException` and my element titleproper (header.getElementsByTagName("titleproper").item(0)) is at start empty that's my String Titleproper which i should parse into nodes ? – Pegazuss Dec 03 '13 at 17:58
  • @Pegazuss I've added some comments to make it clearer. It wasn't obvious from your original example whether `header` is a Document or an Element, if the former then you don't need the `getOwnerDocument()`. You'll also need to add the relevant `import` lines, of course. – Ian Roberts Dec 03 '13 at 18:13
  • my `header`is a Document. Thks a lot i'll try this way tomorrow. – Pegazuss Dec 03 '13 at 20:28