开发者

How do I turn a single word into valid xml?

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);
   In开发者_运维技巧putSource 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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜