What's the most efficient way to find and set element values in an XDocument?
Given the following XML template:
<Request module="CRM" call="list_service_features" id="{ID}">
<block name="auth">
<a name="username" format="text">{USERNAME}</a>
<a name="password" format="password">{PASSWORD}</a>
<a name="client-id" format="counting">{CLIENT-ID}</a>
</block>
<a name="service-id" format="counting">{SERVICE-ID}</a>
</Request>
Using XDocument, best way to set values in curly braces. I am so far, but stuck on the best path to select each of the 3 nodes <a />
within an element <block/>
. This is just a small chunk of XML, others can have up to 20 elements <a name="..."></a>
.
The way the XML was built was not my creation, this is what we have to submit to our provider's web service ... before anyone laughs at the format = "counting" attribute :)
@David - welcomes answer, appreciated. I kind of hoped it would be a little more elegant, curious along the lines:
List<XElement> e = doc.Descendants("a").ToList();
e.Where(x => x.Attributes("name") == "username").Single().Value = "abc";
e.Where(x => x.Attributes("name") == "password").Single().Value = "abc";
Obviously the code above doesn't work, but I thought there <a>
would be an <elegant> one slot for each of the tags
source to share
Does it do it for you? Good property of old descendants.
string xmlInput = ...;
XDocument myDoc = XDocument.Parse(xmlInput);
//
List<XElement> someElements = myDoc.Descendants("a").ToList();
someElements.ForEach(x => x.Value = "Foo");
//
Console.WriteLine(myDoc);
Hmm, I see you have an attribute. You can also do the following:
string xmlInput = //...
XDocument myDoc = XDocument.Parse(xmlInput);
//
List<XText> someText =
myDoc.Descendants()
.Nodes()
.OfType<XText>()
.Where(x => x.Value.StartsWith("{") && x.Value.EndsWith("}"))
.ToList();
//
List<XAttribute> someAttributes =
myDoc.Descendants()
.Attributes()
.Where(x => x.Value.StartsWith("{") && x.Value.EndsWith("}"))
.ToList();
//
someText.ForEach(x => x.Value = "Foo");
someAttributes.ForEach(x => x.Value = "Bar");
//
Console.WriteLine(myDoc);
Now, with what you expect, I'll make it work:
List<XElement> e = myDoc.Descendants("a").ToList();
e.Where(x => x.Attribute("name").Value == "username").Single().Value = "abc";
e.Where(x => x.Attribute("name").Value == "password").Single().Value = "abc";
source to share