1

I've got a node in an XSD that I'd like to modify. I'd like to change the "name" value in this node:

<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">

However when I try to find that node via this code, I get either no nodes or an error, depending on what I try.

xsdDoc.Descendants("element").Where(x => x.Attribute("name").Value == "NewDataSet").Single().SetAttributeValue("name", "newValue");

Linq To Xsd isn't an option, since it looks like it's open source and that will mean all sorts of red tape (at work).

Is this possible, or am I out of luck?

Related (but not the same): Linq to XML - update/alter the nodes of an XML Document

Community
  • 1
  • 1
jcollum
  • 43,623
  • 55
  • 191
  • 321

2 Answers2

3

You need an XNamespace for the "xs" namespace, then you need to use xsdDoc.Descendants(ns+"element").


XNamespace xs = "http://www.w3.org/2001/XMLSchema";
doc.Descendants(xs + "element").
    Where(x.Attribute("name") != null 
    &&  x => x.Attribute("name").Value == "NewDataSet").First().
    SetAttributeValue("name", "newValue");
jcollum
  • 43,623
  • 55
  • 191
  • 321
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • Like so: "http://www.w3.org/2001/XMLSchemaelement"? That doesn't seem right, but I see where you're going... – jcollum Dec 29 '09 at 21:37
  • Ahh, like so: XNamespace xn = "http://www.w3.org/2001/XMLSchema"; IEnumerable elems = xsdDoc.Descendants(xn+"element").Where( x => x.Attribute("name").Value == "NewDataSet"); – jcollum Dec 29 '09 at 21:51
  • This whole XDocument/X* namespace is just a little weird. – jcollum Dec 29 '09 at 21:55
  • It sure looks right, but I'm getting a null ref exception on the lambda the second time I for-each it. – jcollum Dec 29 '09 at 22:20
  • Same result if I do it with .Single().SetAttributeValue() – jcollum Dec 29 '09 at 22:22
  • What fixed it? I found a second bug - need to check for x.Attribute("name") != null before accessing .Value. – John Saunders Dec 29 '09 at 22:34
  • I changed .Single() to .First() and that did it for some reason. Still wrapping my head around lambdas. Apparently. You're right about the null check, that's what was killing me. – jcollum Dec 29 '09 at 23:27
1

Just a guess, but it could be a namespacing problem, try using LocalName, like in this question:

Ignore namespaces in LINQ to XML

Community
  • 1
  • 1
Andy White
  • 86,444
  • 48
  • 176
  • 211