通过 LINQ to XML 在 XDocument 文件的标签内创建 "text<tag />text<tag />" 内容

Creating "text<tag />text<tag />" content inside a tag in an XDocument file via LINQ to XML

我正在使用 XDocument class 和 LINQ to XML 创建一些简单的 HTML 输出,我偶然发现了一个我似乎无法解决的问题解决。使用 XML.

时甚至根本不可能

我有一个包含很多属性的 POCO,其中一些属性是按约定命名的,因此我使用反射来迭代它们,类似于以下内容:

List<string> propSuffixes = new List<string>();
for (int i=1; i<=20; i++)
{
  propSuffixes.Add(i.ToString("D2")); // "01", "02", ..., "20"
}

XDocument xDoc = new XDocument(
  new XElement("html",
    new XElement("body",
      propSuffixes
        .Select(suffix =>
          (string)typeof(MyPOCO)
          .GetProperty("p" + suffix)
          .GetValue(myPocoInstance))
        .Select(v =>
          new XElement("span", v, new XElement("br"))))));

这会将 20 个属性的字符串值放在它们自己的 <span> 中,并带有一个 <br /> 标记。但是我想要 "just" 没有跨度的字符串值,但在每行的末尾仍然有 <br /> 。也就是像这样:

<html>
  <body>
    propertyValue1<br />
    propertyValue2<br />
    ...
    propertyValue20<br />
  </body>
</html>

这是否可能,或者这是否违反某些 XML 验证规则?如果可能的话,我怎样才能用 LINQ 做到这一点?对我来说,困难在于必须 return 2 object 参数到 new XElement("body",...) 的参数,但我也不知道如何在 string 之前传递 string =18=] 到参数而不引发一些错误。

你知道有什么方法可以实现我的目标,或者实现类似的布局(也许我可以使用 <p> 而不是 string 加上 <br />)?

您可能无法获得行尾的 <br />,但您当然可以拆分文本和标签,例如:

XElement root = new XElement("root");
root.Add(
    new XText("Text"), 
    new XElement("tag"),
    new XText("Text"), 
    new XElement("tag"), 
    new XText("Text"));