code_junkie

What's the most efficient way to locate and set element values in an XDocument?

Nov 12th, 2011
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. <Request module="CRM" call="list_service_features" id="{ID}">
  2. <block name="auth">
  3. <a name="username" format="text">{USERNAME}</a>
  4. <a name="password" format="password">{PASSWORD}</a>
  5. <a name="client-id" format="counting">{CLIENT-ID}</a>
  6. </block>
  7. <a name="service-id" format="counting">{SERVICE-ID}</a>
  8. </Request>
  9.  
  10. List<XElement> e = doc.Descendants("a").ToList();
  11. e.Where(x => x.Attributes("name") == "username").Single().Value = "abc";
  12. e.Where(x => x.Attributes("name") == "password").Single().Value = "abc";
  13.  
  14. string xmlInput = ...;
  15. XDocument myDoc = XDocument.Parse(xmlInput);
  16. //
  17. List<XElement> someElements = myDoc.Descendants("a").ToList();
  18. someElements.ForEach(x => x.Value = "Foo");
  19. //
  20. Console.WriteLine(myDoc);
  21.  
  22. string xmlInput = //...
  23. XDocument myDoc = XDocument.Parse(xmlInput);
  24. //
  25. List<XText> someText =
  26. myDoc.Descendants()
  27. .Nodes()
  28. .OfType<XText>()
  29. .Where(x => x.Value.StartsWith("{") && x.Value.EndsWith("}"))
  30. .ToList();
  31. //
  32. List<XAttribute> someAttributes =
  33. myDoc.Descendants()
  34. .Attributes()
  35. .Where(x => x.Value.StartsWith("{") && x.Value.EndsWith("}"))
  36. .ToList();
  37. //
  38. someText.ForEach(x => x.Value = "Foo");
  39. someAttributes.ForEach(x => x.Value = "Bar");
  40. //
  41. Console.WriteLine(myDoc);
  42.  
  43. List<XElement> e = myDoc.Descendants("a").ToList();
  44. e.Where(x => x.Attribute("name").Value == "username").Single().Value = "abc";
  45. e.Where(x => x.Attribute("name").Value == "password").Single().Value = "abc";
Add Comment
Please, Sign In to add comment