Happy Singh
Happy Singh

Reputation: 95

c# - Find node value without root element

This is my column value in sql:

<ProductId>101</ProductId>
<ProductName>TShirt</ProductName>
<Description>UCB</Description>
<Category>199</Category>
<Weight>150</Weight>
<Price>2500</Price>
<images></images>

Sometimes it looks like this also:

<ProductId xsi:nil="true" ></ProductId> 
<ProductName>Toys</ProductName>
<Description xsi:nil="true" ></Description>
<Category xsi:nil="true" ></Category>
<Weight xsi:nil="true" ></Weight>
<Price xsi:nil="true" ></Price>
<images></images>

I want to extract 'ProductName' value i.e. TShirt from this column. It could be any node, How do I do this?

This is my c# code

var xml = XElement.Parse(xmlString);

string fieldValue = xml.Element(fieldToSearch).ToString();

But since it is not proper xml string it gives error so I wrote explicitly

string xmlString = "<root>" + columnValue + "</root>";

What is the correct way to find the node value?

Edit: The value can be extrtacted for Weight/Description/Price, any node. The error comes when xsi:nil is found.

Upvotes: 2

Views: 398

Answers (1)

Charles Mager
Charles Mager

Reputation: 26223

You're getting an error because the xsi:nil attribute has a namespace prefix of xsi. As you're missing the parent element, there's no declaration of this prefix.

Ideally, you'd fix the source of this so that you store well formed XML rather than a bunch of child elements, but if you're stuck with it then the easiest way to get around the issue is to add the namespace declaration to your dummy root element:

var xmlString = 
    "<root xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + 
    columnValue + 
    "</root>";

Secondly, I'd note that ToString() will return the element itself, e.g. <ProductName>Toys</ProductName>. If you just want the value, then you can use the explicit conversion:

var fieldValue = (string) xml.Element(fieldToSearch);

See this fiddle for a working demo.

Upvotes: 2

Related Questions