<分区>
(注意:最初的问题标题是:从具有文档规范的字符串加载 XML 的最佳方法是什么?)
我需要从 XmlDocument 对象中的 ODT opendocument (LibreOffice) 文件中获取 XML 内容。 ODT 是一个 zip 存档,我设法将 content.xml 部分作为字节数组获取。转换为字符串看似简单,但我惊讶地发现 XmlDocument.LoadXml(string) 不接受以 Xml 文档规范行开头的字符串,例如:
<?xml version="1.0" encoding="UTF-8"?>
<Offices id="0" enabled="false">
<office />
</Offices>
异常(exception)情况是:根级别的数据无效。第 1 行,位置 1
不知是否有库调用读取这样的字符串?
现在我使用这个我即兴创作的函数,但是在处理 xml 文档时必须在字符级别上做一些事情感觉不必要的复杂:
/// <summary>
/// Convert an Xml document in a string, including document specification line(s),
/// to an XmlDocument object
/// </summary>
/// <param name="XmlString"></param>
/// <returns></returns>
public static XmlDocument LoadXmlString(string XmlString)
{
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.LoadXml(XmlString.Substring(XmlString.LastIndexOf("?>") + 2));
return XmlDoc;
}
有没有更好的办法?
注意:我指的是 this earlier question
但这解决了解析字符串的问题,将字符串转换为字节数组的解决方案,而我不应该解析字符串,而不是首先将字节数组转换为字符串,而只是跳过这个步骤,直接解析ODT解压后的字节数组。