【问题标题】:Creating XML document using Linq to XML in C#在 C# 中使用 Linq to XML 创建 XML 文档
【发布时间】:2013-05-26 02:09:44
【问题描述】:

我正在使用下面提到的代码在 C# 中创建 XML:

     XDocument xDoc = new XDocument(new XDeclaration("1.0", "UTF-16","yes"),
          new XElement("Parent",
          from childItem in childItemList
          select new XElement("Child",
                    new XElement("source",childItem.Source),
                    new XElement("target", childItem.Target)
                    )));

它工作正常,文档按预期创建。但是我想写

    childItem.Source 
    childItem.Target

作为属性值,我为此使用了以下代码:

    XDocument xDoc = new XDocument(new XDeclaration("1.0", "UTF-16","yes"),
          new XElement("Parent",
          from childItem in childItemList
          select new XElement("Child",
                  (new XAttribute("value", childItem.Source))),
              new XElement("target", 
                 (new XAttribute("value",childItem.Target)))
               )));

此代码也可以正常工作,但问题是我在

中有多行文本
    childItem.Source
    childItem.Target

当将其写为节点的内部文本时,它可以正常工作,但是当将其写为属性值时,多行文本将被转换为单行文本。我想按原样保留 XML 文档中的所有空格和换行符。任何帮助表示赞赏。

【问题讨论】:

    标签: c#-4.0 linq-to-xml


    【解决方案1】:

    属性中不能有换行符 (CRLF)!为了“安全”,换行符总是从 XElement 类转换为十六进制文字。我想这是为了符合 HTTP(或其他一些网络协议) - 例如在 URI 中不允许换行。您始终可以从您拥有的十六进制值中恢复您的 CRLF。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多