[英]XPath to select nodes whose name starts with
I have XML that looks like this: 我有看起来像这样的XML:
<detail>
<address>
<line1/>
<line2/>
<line3/>
<postcode/>
</address>
</detail/>
There could be any number of <line*>
nodes which I want to select, and other nodes which I don't want to select. 我可以选择任意数量的
<line*>
节点,而其他我不想选择的节点。
I have tried this, which doesn't seem to work (in C# anyway): 我已经尝试过了,但这似乎不起作用(无论如何在C#中):
/detail/address/[substring(name(),4) = 'line']
Al, help appreciated! 铝,帮助赞赏!
尝试
/detail/address/*[starts-with(name(), 'line')]
From memory, I think the index is 1 based not 0 based. 从内存来看,我认为索引是基于1而不是基于0。 Perhaps this will work:
也许这会起作用:
/detail/address/[substring(name(),1,3) = 'line']
Alternatively, do you have control over the format of the XML? 另外,您可以控制XML格式吗? If so, a better approach might be to structure it like so:
如果是这样,一个更好的方法可能是像这样构造它:
<detail>
<address>
<line number='1'/>
<line number='2'/>
<line number='3'/>
<postcode/>
</address>
</detail/>
Then you can use the following to retrieve the lines: 然后,您可以使用以下内容检索行:
/detail/address/line
Consider using XDocuments. 考虑使用XDocuments。
XDocument doc = XDocument.Parse(xmlString);
foreach (XElement element in doc.Descendants())
{
if(element.Name.LocalName.StartsWith("line"))
//DoStuffWithValueOfThatElement(element.Value)...
}
You can try with contains
: 您可以尝试使用
contains
:
/detail/address/*[contains(name(),'line')]
If you want to use substring
you've to know that the index starts with 1 and you're also missing the wildcard: 如果要使用
substring
,则必须知道索引以1开头,并且还缺少通配符:
/detail/address/*[substring(name(),1,4) = 'line']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.