views:

43

answers:

2

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): http://stackoverflow.com/questions/331502/linq-to-xml-update-alter-the-nodes-of-an-xml-document

+2  A: 

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");
John Saunders
Like so: "http://www.w3.org/2001/XMLSchemaelement"? That doesn't seem right, but I see where you're going...
jcollum
Ahh, like so: XNamespace xn = "http://www.w3.org/2001/XMLSchema"; IEnumerable<XElement> elems = xsdDoc.Descendants(xn+"element").Where( x => x.Attribute("name").Value == "NewDataSet");
jcollum
This whole XDocument/X* namespace is just a little weird.
jcollum
It sure looks right, but I'm getting a null ref exception on the lambda the second time I for-each it.
jcollum
Same result if I do it with .Single().SetAttributeValue()
jcollum
Fixed, will edit OP.
jcollum
What fixed it? I found a second bug - need to check for x.Attribute("name") != null before accessing .Value.
John Saunders
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
+1  A: 

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

http://stackoverflow.com/questions/1145659/ignore-namespaces-in-linq-to-xml

Andy White