2016-06-11 65 views
0

我有以下使用命名空间的XML结构:复制XML属性使用LINQ

<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。现在我只想复制内部文本为“<Text >”的属性,并将副本替换为新文本。我试过这个:

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> 

回答

1

如果我理解正确的话,你需要的<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(...); 
+0

不但。我需要复制该属性,以便我有两个相同的属性,然后替换该副本的值。 – Canox

+0

@Canox - 显示所需结果 –

+0

好的我编辑了我的问题 – Canox

0

试试这个

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); 
 
     } 
 
    } 
 
}

+0

我想这不是我正在寻找的,因为值被更改,但没有创建新的属性。我编辑了我的问题。希望现在更清楚 – Canox