tags:

views:

87

answers:

1

Hello,
I have some xml:

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

I would like to add an attribute to each item:

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

Is that possible with LINQ in C#? Thanks any tips...

A: 

Sure. See the following link: 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" ) ) );

You can see above that it builds out the XML structure with nested calls. All you need to do is include the 'new Attribute' call as part of the LINQ structure to generate a new attribute.

UPDATE: If you want to add attributes to the result of a query, do the following:

var query = from node in xml.Descendants( "element" )
            select node;

foreach( var element in query )
{
    element.SetAttributeValue( "status", "running" );
}
j0rd4n
Thanks for the reply.I don't need to create a new element, I want to add the attribute to all the existing elements...I could probably select all elements in to a query, iterate through the query adding the attribute, then save the query back as the original doc, but that seems rather inelegant.
Number8
Oh I see what you are saying. Why do you not like the technique you mentioned?
j0rd4n
See my updated comment above.
j0rd4n
Thanks, that's similar to what I'm doing, but I add each node to a new document. Is there a way to replace the original XDocument with the query?
Number8
If I'm not mistaken from what you are saying, you would just call Save() on the XElement and use the same name as the XDocument file you created.
j0rd4n
No files involved, only in-memory objects. The XDocuments are originally created by redirecting stdout from a console process.
Number8
"...just call Save() on the XElement..." Is the query an XElement?
Number8
The query portion is just modifying the original XElement (in our example named 'xml'). So once you run the query, the original XElement will be modified as is in memory.
j0rd4n