0

I have the following code which turns a string, that I pass into the function, into a document:

DocumentBuilderFactory dbFactory_ = DocumentBuilderFactory.newInstance();
Document doc_;

void toXml(String s)
{
   documentBuild();
   DocumentBuilder dBuilder = dbFactory_.newDocumentBuilder();
   StringReader reader = new StringReader(s);
   InputSource inputSource = new InputSource(reader);
   doc_ = dBuilder.parse(inputSource);
}

The problem is that some of the legacy code that I'm using passes into this toXml function a single word like RANDOM or FICTION. I would like to turn these calls into valid xml before trying to parse it. Right now if I call the function with s = FICTION it returns a SAXParseExeption error. Could anyone advise me on the right way to do this? If you have any questions let me know.

Thank you for your time

-Josh

Grammin
  • 11,808
  • 22
  • 80
  • 138
  • 2
    First you'll need to detail **exactly** what valid XML output you want when someone is passing in the string `FICTION`. The current behaviour is arguably correct, because that *isn't* valid XML, so you'll have to perform some kind of transformation in order to "wrap" it in an XML document. – Andrzej Doyle Jan 27 '11 at 18:21

2 Answers2

1

Have you tried the seemingly obvious <FICTION/> or <FICTION></FICTION>?

Anonymoose
  • 5,662
  • 4
  • 33
  • 41
  • Well yea that was my first instinct but the problem with that is then im going to have to do string operations to check and add '<' and '/' I sorta want something that will do that for me. – Grammin Jan 27 '11 at 18:52
  • @Grammin I'm afraid you can't really escape that, as an XML document **must** have a root element at least. – biziclop Jan 27 '11 at 19:25
1

This creates an XmlDocument with an element test

function buildXml(string s) {
    XmlDocument d = new XmlDocument();
    d.AppendChild(d.CreateElement(s));

    StringWriter sw = new StringWriter();
    XmlTextWriter xw = new XmlTextWriter(sw);
    d.WriteTo(xw);
    return sw.ToString();
}

buildXml("Test"); //This will return <Test />

Its a bit ugly but it will create the XML without having to do any string work on your own ;)

You could add this in a try catch in your method so if it fails to load it as an XML directly it passes the string to this and then tries to load it.

David Mårtensson
  • 7,550
  • 4
  • 31
  • 47
  • Thank you for the answer david, this is exactly what I wanted except sometimes the string that I enter is already valid xml. How do I check if my string s is valid xml or not? – Grammin Jan 27 '11 at 19:23
  • "You could add this in a try catch in your method so if it fails to load it as an XML directly it passes the string to this and then tries to load it." Awesome solution thank you very much! – Grammin Jan 27 '11 at 19:24
  • Pretty slick. I hope it's not expected to perform very well, though ;) – Anonymoose Jan 27 '11 at 23:52