【发布时间】:2019-03-08 12:18:42
【问题描述】:
这是我在 sql 中的列值:
<ProductId>101</ProductId>
<ProductName>TShirt</ProductName>
<Description>UCB</Description>
<Category>199</Category>
<Weight>150</Weight>
<Price>2500</Price>
<images></images>
有时它也是这样的:
<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>
我想从该列中提取“ProductName”值,即 TShirt。它可以是任何节点,我该怎么做?
这是我的 C# 代码
var xml = XElement.Parse(xmlString);
string fieldValue = xml.Element(fieldToSearch).ToString();
但由于它不是正确的 xml 字符串,它会给出错误,所以我明确写了
string xmlString = "<root>" + columnValue + "</root>";
找到节点值的正确方法是什么?
编辑:可以为重量/描述/价格,任何节点提取值。找到 xsi:nil 时出现错误。
【问题讨论】:
-
有什么方法可以改变数据在 SQL 中的存储方式?你所做的可能是好的,但存储无效的 xml 有点我 imo
-
我会将 xml 包装在一个根节点中,类似于您的操作方式,也许不是通过字符串连接,但这应该可以。有什么问题?
-
该错误是由于内部文本为空。尝试以下操作: string fieldValue = (string)xml.Element(fieldToSearch; ToString() 将在 null 时失败。
-
It could be any node这意味着您的TShirt值出现在任何列上?或<ProductName> -
如果 element 为空,@jdweng
ToString()将失败,这只会在它丢失时发生。如果 value 为 null 或为空,则没有问题。