1

I have sample xml string

<root><a>textA</a><b>textB</b></root>

I want to split/traverse this xml using java split function to have an array where each element and its values are placed one after the other, so that I could manipulate them easily.

I tried

     split("(?=<)|(?<=>)")

but this is returning me root elements as well as closing tags in the array along with one element (additional space string ). Thanks in advance (Option of chosing XML parser is not feasible right now ).

8
  • 7
    Don't use this sort of thing to deal with XML - use a dedicated XML parser instead (such as the built in DOM parser), it's much less prone to errors. Commented Jul 4, 2014 at 0:12
  • You are right ...but as of now , we dont have option to use that parser due to some constraints (most of the code is already in prod) ..we need to do string manipulation somehow to take this further.. I know this is ugly but cant help it for now.. Commented Jul 4, 2014 at 0:20
  • I'm not really sure I understand your constraints - you can modify the code, but you're not allowed to modify the code to use the standard java XML parsers? Would that incur too much test overhead? I don't get it. Commented Jul 4, 2014 at 0:43
  • I agree with others: string manipulation will only get you so far, and will likely only work for really simple XML. The only way around not using XML parsers (why on Earth not considering one comes embedded as part of J2SE ?), would be to write your own recursive parser, which is to say: reinvent the Wheel. split() is not an option, as the whole idea of XML is nested elements, which means a linear array is not suited to representing XML data. Commented Jul 4, 2014 at 1:01
  • 1
    How do you have String.split() in production but not DocumentBuilderFactory? Commented Jul 4, 2014 at 3:02

1 Answer 1

1
String[] split = s.split("<.*?>");

then filter the empty data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.