bouncingHippo
bouncingHippo

Reputation: 6040

best way for parsing an xml string and trimming spaces for specific tags using java

Imagine i have an xml-formatted string

String gandalfSchema = "<Wizard><Name> Gandalf </Name><God Mode>Off</God Mode></Wizard>";

I want to remove all leading and trailing spaces for values for multiple tags; in this case Gandalf in <Name>.

I'm not sure if the following way is the best:

String nameBeginIndex = gandalfSchema.substring("<Name>");
String nameEndIndex = gandalfSchema.substring("</Name>");
String nameRaw = gandalfSchema.substring(nameBeginIndex+6,nameEndIndex);
String nameProcessed = nameRaw;
String stringBeforeNameRaw = gandalfSchema.substring(nameBeginIndex);
String stringAfterNameRaw = gandalfSchema.substring(nameEndIndex);
gandalfSchema = stringBeforeNameRaw + nameProcessed + stringAfterNameRaw

Now imagine doing the above for 3-4 tags, i think that is bad practice. Is there a library, or convention in Java for this that I may have overlooked?

Upvotes: 2

Views: 1320

Answers (4)

hopeIsTheonlyWeapon
hopeIsTheonlyWeapon

Reputation: 567

Yes use jaxb that comes with Java and using any IDE you can create the xml classes and can Marshall and uarshall in much better and easier way You need to know your Xsd and that you can get online if you have the xml ready

Upvotes: 0

Dragan Bozanovic
Dragan Bozanovic

Reputation: 23552

You could use XSLT with Java Transformer API. Here is a similar example to get you started.

Upvotes: 0

Sean F
Sean F

Reputation: 2390

I would suggest using JaxB and actually create objects based on your xml

Wizard Class

@XmlRootElement(name="Wizard")
public class Wizard {

    private String name;
    private String godMode;


    public String getName() {
        return this.name;
    }

    @XmlElement(name="Name")
    public void setName(String name) {
        this.name = name;
    }

    public String getGodMode() {
        return this.godMode;
    }

    @XmlElement(name="GodMode")
    public void setGodMode(String godMode) {
        this.godMode = godMode;
    }
}

Then use an unmarshalled to get the object from xml

Unmarshaller

JAXBContext jaxbContext = JAXBContext.newInstance(Wizard.class);

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

StringReader reader = new StringReader("<Wizard><Name> Gandalf </Name><GodMode>Off</GodMode></Wizard>");
Wizard wizard = (Wizard) unmarshaller.unmarshal(reader);

and then you can do what ever you want with it. Also "God Mode" has a space and that does not work for element names (if possible change this, or you might have to do a find replace on this before unmarshalling).

Upvotes: 0

Raman Shrivastava
Raman Shrivastava

Reputation: 2953

What you need is XML Parsers. There are already so many available. Google it. Why reinvent the wheel, unless you're trying to build new parser itself (which is quite unlikely).

Upvotes: 1

Related Questions