如果属性等于预定义字符串,则选择节点

时间:2015-11-25 15:14:08

标签: c# xml xpath

我目前正在使用一个循环,它给我一个变量,然后需要将其输入到Xpath方法中,以获得属性等于my变量的任何节点。到目前为止,我已经了解到Xpath允许您使用

从XML文档中选择一个节点
root.SelectNodes("Element[@Attribute='SpecificValue']")

但是,我想知道是否有可以在特定值中插入预定义变量的方法,因此我可以在循环的每次迭代中获取不同的节点集。

例如:

string  attribValue= "test"
root.SelectNodes("Element[@Attribute = attribValue]")

2 个答案:

答案 0 :(得分:1)

使用string formatting

string attribValue = "test";
string expression = String.Format("Element[@Attribute = '{0}']", attribValue);
root.SelectNodes(expression);

答案 1 :(得分:0)

使用XML Linq



create table #table_name
(
    unit varchar(3),
    label varchar(10),
    [date] varchar(10),
    value varchar(10),
    [time] varchar(10),
)


declare @s varchar(1000) = 'a,2015-10-08,1451,1,2,3,4,5,6,7,8,9,10,11;a,2015-10-08,1721,12,13,14,15,16,17,18,19,20,21,22'
declare @units varchar(1000) = 'l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11'
set @units = '@label,@date,@hour,'+@units
;with cte as (select b.value,c.value as unit, a.orderCol as ri from dbo.explode(@s,';') a
cross apply dbo.explode(value,',') b
inner join dbo.explode(@units,',') c
    on b.orderCol = c.orderCol),
topCte as (
select c4.unit as unit
    ,(case 
        when len(c3.value) <= 3 then '0' + substring(c3.value,1,1) + ':' + substring(c3.value,2,2) 
        else (substring(c3.value,1,2) + ':' + substring(c3.value,3,2))
        end+':00') as [time]
    ,c1.value as label
    ,c2.value as [Date]
    ,c4.value
from cte c1
inner join cte c2
    on c1.ri = c2.ri and c1.unit = '@label' and c2.unit = '@date'
inner join cte c3
    on c1.ri = c3.ri and c3.unit = '@hour'
inner join cte c4
    on c1.ri = c4.ri and c4.unit not in ('@label','@date','@hour')
)
insert into #table_name(unit, label, [date], value, [time])
select unit, label, [date], value,  [time] 
from topCte

select unit, label, [date], value, cast([time] as time) 
from #table_name
&#13;
&#13;
&#13;