作为项目的一部分,我需要从一些似乎不是标准XML的XML中解析一些值。 XML存储在SQL Server中。我需要查询数据库并检索此XML,然后在C#中我需要获取XCoord和YCoord字段的值。有人可以告诉我如何使用System.Xml实现这一点吗?
如果有人知道SQL查询从XML数据中返回这些值,那也可以。
<AdapterItem xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.enceladus.com/Data">
<Attributes>
<Attribute>
<Name>Process ID</Name>
<Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">1000</Value>
</Attribute>
<Attribute>
<Name>Request</Name>
<Value i:type="AdapterItem">
<Attributes>
<Attribute>
<Name>Location</Name>
<Value i:type="AdapterItem">
<Attributes>
<Attribute>
<Name>XCoord</Name>
<Value xmlns:d10p1="http://www.w3.org/2001/XMLSchema" i:type="d10p1:string">482557.53208923</Value>
</Attribute>
<Attribute>
<Name>YCoord</Name>
<Value xmlns:d10p1="http://www.w3.org/2001/XMLSchema" i:type="d10p1:string">240588.72462463</Value>
</Attribute>
</Attributes>
</Value>
</Attribute>
<Attribute>
<Name>Description</Name>
<Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">Some Description</Value>
</Attribute>
</Attributes>
</Value>
</Attribute>
</Attributes>
</AdapterItem>
提前致谢!
答案 0 :(得分:1)
这是C#解决方案:
var doc = new XmlDocument();
doc.LoadXml(columnValueFromSql);
Console.WriteLine("XCoord={0}, YCoord={1}",
doc.SelectSingleNode("//Attribute[Name='XCoord']/Value").InnerText,
doc.SelectSingleNode("//Attribute[Name='YCoord']/Value").InnerText);
/* Outputs:
XCoord=482557.53208923, YCoord=240588.72462463
*/
答案 1 :(得分:0)
你可以写一些与此相似的内容,
WITH XMLNAMESPACES (http://www.w3.org/2001/XMLSchema' AS d4p1,
'http://schemas.enceladus.com/Data' AS message)
SELECT
CAST([XML_DATA] AS XML).value('(/AdapterItem/Attributes/Attribute[2]/Value/Attributes/Attribute[1]/Value/Attributes/Attribute[1]/Value)[1]', 'VARCHAR(20)') AS 'XCoord',
CAST([XML_DATA] AS XML).value('(/AdapterItem/Attributes/Attribute[2]/Value/Attributes/Attribute[1]/Value/Attributes/Attribute[2])[1]', 'VARCHAR(20)') AS 'YCoord' FROM YOURTABLE
答案 2 :(得分:0)
SQL Server查询如下所示:
with xmlnamespaces(default 'http://schemas.enceladus.com/Data')
select T.XMLCol.value('(//Attribute[Name = "XCoord"]/Value/text())[1]', 'varchar(20)') as XCoord,
T.XMLCol.value('(//Attribute[Name = "YCoord"]/Value/text())[1]', 'varchar(20)') as YCoord
from YourTable as T