【问题标题】:In XML, how do you ignore dangling text that is not surrounded by tags?在 XML 中,如何忽略没有被标签包围的悬空文本?
【发布时间】:2013-10-18 23:57:35
【问题描述】:

我遇到了这个问题,我正在阅读的 xml 文件可能有悬空文本(我不知道那些没有被任何标签包围的文本叫什么)。

例如:

<Book>
    <Title>The Catcher in the Rye</Title>
    <Author>Salinger</Author>
</Book>
Useless jiberish
<Book>
    <Title>Jaws</Title>
    <Author>Benchley</Author>
</Book>

这是完美的 xml,除了“无用的 jiberish”这一行。读取没有任何问题,但是使用带有

的 streamwriter 写入
XmlWriterSettings settings = new XmlWriterSettings();
settings.NewLineOnAttributes = true;
settings.Indent = true;

它写得很完美,直到出现“无用的胡言乱语”的那一行

<Book>
    <Title>The Catcher in the Rye</Title>
    <Author>Salinger</Author>
</Book>Useless jiberish<Book><Title>Jaws</Title><Author>Bencheley</Author>

如果我从 xml 文档中删除“无用的 jiberish”,它会完美运行。但是我没有那个选项。关于为什么会发生这种情况,有什么建议/线索吗?这可能是我想念的非常简单的事情。

任何建议都有帮助。

谢谢。

【问题讨论】:

  • 你是在读还是写那个xml
  • 我都在做。从我看到的读数来看,处理得当。但是,当我使用 MemoryStream 将其写回时,它并没有正确写回。
  • 向我们展示您用于编写 xml 的代码

标签: c# xml file-io io xmlwriter


【解决方案1】:

您可能会考虑使用 System.Xml.Linq 中的 XDocument 类。加载文件看起来像:

        string file = @"c:\test\movies.xml";
        XDocument doc = XDocument.Load(file);
        foreach (XElement e in doc.Root.Descendants())
        {

        }

有关 XDocument 的更多信息here

【讨论】:

    猜你喜欢
    • 2010-12-07
    • 1970-01-01
    • 2015-02-02
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    相关资源
    最近更新 更多