0

我有以下代码将传递给函数的字符串转换为文档:

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);
}

问题是我正在使用的一些遗留代码传递给这个 toXml 函数一个像RANDOMor之类的单词FICTION。在尝试解析之前,我想将这些调用转换为有效的 xml。现在,如果我用 s = FICTION 调用该函数,它会返回一个SAXParseExeption错误。任何人都可以告诉我正确的方法吗?如果您有任何问题,请告诉我。

感谢您的时间

-乔什

4

2 回答 2

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.

于 2011-01-27T19:19:04.893 回答
1

您是否尝试过看似明显的<FICTION/><FICTION></FICTION>

于 2011-01-27T18:25:11.007 回答