使用 Linq 复制 Xml 属性

Copy an Xml Attribute with Linq

我有以下带有命名空间的 xml 结构:

<office:document-content
<office:body>
<office:text text:use-soft-page-breaks="true">
  <text:p text:style-name="Standard">&lt;Text&gt;</text:p>
</office:text>
</office:body>
</office:document-content>

这来自解压缩的 .odt 编写器文件的 content.xml。现在我只想复制带有内部文本“”的属性并用新文本替换副本。我试过这个:

    XmlFileOperations xml = new XmlFileOperations();
        XDocument doc = XDocument.Load(Path.Combine(ConfigManager.InputPath, "File", "content.xml"));

        var source = doc.Descendants()
            .Where(e => e.Value == "<Text>")
            .FirstOrDefault();
        var target = new XElement(source);
        target.Add(new XAttribute("Standard", source.Attribute(textLine)));

        doc.Save(Path.Combine(ConfigManager.InputPath, "File", "content.xml"));

这不起作用。它告诉我,我在文本中有一个不能应用于名称的符号。在这种情况下我如何才能复制我的属性?

谢谢!

编辑:结果应该是

<office:document-content
<office:body>
<office:text text:use-soft-page-breaks="true">
  <text:p text:style-name="Standard">&lt;Text&gt;</text:p>
  <text:p text:style-name="Standard">some new value</text:p>
</office:text>
</office:body>
</office:document-content>

如果我没理解错的话,您需要将 <Text> 的值替换为 textLine

试试这个代码

var source = doc.Descendants()
    .Where(e => !e.HasElements && e.Value == "<Text>")
    .FirstOrDefault();

var target = new XElement(source);
target.Value = textLine;
source.AddAfterSelf(target);

doc.Save(...);

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
         
            XElement doc = XElement.Load(FILENAME);
            XElement p = doc.Descendants().Where(x => x.Name.LocalName == "p").FirstOrDefault();
            XAttribute name = p.Attributes().Where(x => x.Name.LocalName == "style-name").FirstOrDefault();
            name.Value = "new value";
            doc.Save(FILENAME);
        }
    }
}