【问题标题】:LINQ to update an XDocumentLINQ 更新 XDocument
【发布时间】:2009-08-14 19:22:31
【问题描述】:

我有一些 xml:

<Response TaskId="2429">
  <message>Run for cover.</message>
  <element location="proj\survival.cs"/>
  <element location="proj\run.cs"/>
</Response>

我想为每个项目添加一个属性:

<element location="proj\run.cs" status="running"/>

在 C# 中使用 LINQ 可以吗? 感谢任何提示...

【问题讨论】:

    标签: xml linq


    【解决方案1】:

    当然。见以下链接:http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx

    XElement xml = new XElement( "Response", 
                                 new XAttribute( "TaskId", "2429" ),
                                 new XElement( "message", "Run for cover" ),
                                 new XElement( "element",
                                     new XAttribute( "location", "proj\survival.cs" ),
                                     new XAttribute( "status", "running" ) ),
                                 new XElement( "element",
                                     new XAttribute( "location", "proj\run.cs" ),
                                     new XAttribute( "status", "running" ) ) );
    

    您可以在上面看到它使用嵌套调用构建了 XML 结构。您需要做的就是在 LINQ 结构中包含“新属性”调用以生成新属性。

    更新:如果要向查询结果添加属性,请执行以下操作:

    var query = from node in xml.Descendants( "element" )
                select node;
    
    foreach( var element in query )
    {
        element.SetAttributeValue( "status", "running" );
    }
    

    【讨论】:

    • 感谢您的回复。我不需要创建新元素,我想将属性添加到所有现有元素......我可能会选择查询中的所有元素,遍历查询添加属性,然后将查询另存为原始文档,但这似乎不太优雅。
    • 哦,我明白你在说什么。你为什么不喜欢你提到的技术?
    • 谢谢,这与我正在做的类似,但我将每个节点添加到一个新文档中。有没有办法用查询替换原来的 XDocument?
    • 如果我没听错的话,您只需在 XElement 上调用 Save() 并使用与您创建的 XDocument 文件相同的名称。
    • 不涉及文件,只涉及内存对象。 XDocument 最初是通过从控制台进程重定向标准输出来创建的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多