English 中文(简体)
在SAX解析器中传递未知的XML元素
原标题:
  • 时间:2008-10-30 16:34:30
  •  标签:

I am loading some data from an XML document, modifying it, and writing back out to XML. The reading is done using a SAX parser library and the writing is done with a piece of custom code. Sometimes, the file is modified externally, and extra elements are added (such as references to stylesheets). Rather than losing these extra elements when I load and save the file, I would like to pass through any unknown tags so that they appear

当未知元素与已解释元素分离时,将未知元素和属性保存为字符串并在之后输出应该很直观,但当它们交错和嵌套在已解释元素内时,情况就不那么明显了。

Can anybody suggest a succinct way to do this? Would it be simpler to switch to a DOM parser? Performance is not an issue.

NB. I am working in C++ with the Gnome Glib::Markup::Parser, but would prefer language/library agnostic answers.

问题回答

我不知道您是如何编写您的内容处理程序的,但它的方法应该在所有事件上被调用,包括您想要保留的外部修改。您的startElement()endElement()回调可以测试元素名称和属性,以决定是否在要修改的元素上调用专门的方法,但默认情况下,只需重建并输出调用回调的事件。通过这种方式,您没有特别处理的任何元素都将默认输出。

You could also do the same kind of thing in XSLT. Take an identity transform (a stylesheet that outputs exactly what it is given for input) and add to it templates with more specific match expressions for the custom modifications. I find XSLT easier to work with for most applications than either SAX or DOM.

I believe SAX is not the right way to go when you want to modify an xml file and save it back to some other file after being altered. My advice is to use DOM. It will load the entire file (including the modifications done externally) so that you just have to think about what you want to do. Everything will be back in place when you save it afterwards.





相关问题
热门标签