代码之家  ›  专栏  ›  技术社区  ›  Kevin Coppock

是否通过XNA中的streamreader替换XML文件中的单词?

  •  1
  • Kevin Coppock  · 技术社区  · 15 年前

    好吧,这有点像黑客……但可能是。我在XNA中编写了一个应用程序,从我对这个问题的研究来看,它显然不支持XML版本1.1。我正在阅读一个epub文档的内容,其中一本更新的书将其内容编码为1.1XML文档。这会导致我的程序崩溃,但是,结构与其余的相同。唯一能阻止它工作的是xmldocument类中硬编码的“1.0”。

    是否可以从流中读取该文件,查看它是否包含:

    <?xml version="1.1" encoding="UTF-8" standalone="no"?>

    只需将其替换为“1.0”?然后我可以将它作为一个XML文档拉入。我没有对文件进行任何写入,也没有进行任何复杂的结构读取,只是查找一些特定的节点,并拉入值,所以我不知道这会产生什么后果。

    1 回复  |  直到 13 年前
        1
  •  2
  •   Blair Holloway    15 年前

    通过将整个XML文件读取到内存中并按照自己的方式处理,您可以非常巧妙地做到这一点:

    string content = "";
    
    // Read the XML file into content
    StreamReader reader = new StreamReader("file.xml");
    content = reader.ReadToEnd();
    reader.Close();
    
    // Find the character position just after the <?xml token, and just before the ?> token
    int openIndex = content.IndexOf("<?xml", StringComparison.OrdinalIgnoreCase) + 5;
    int closeIndex = content.IndexOf("?>", openIndex);
    
    // Get the bits between <?xml and ?>    
    string header = content.Substring(openIndex, closeIndex - openIndex);
    
    // Substitute version string.
    header = header.Replace("version=\"1.1\"", "version=\"1.0\"");
    
    // Put Humpty Dumpty back together again.
    content = string.Concat(content.Substring(0, openIndex), header, content.Substring(closeIndex));
    
    // Feed content into an XMLReader (or equivalent) here.
    

    它适用于您提供的示例字符串,但我还没有在格式不完善的XML文档上对其进行测试。