如何查找名称以某个字符串开头的XML文件的元素

时间:2021-11-11 19:24:38

I have a list of xml elements that i need to search for specific types of elements that beging with the text "UserName". The elements i also have a number after the "UserName" text so they look like this:

我有一个xml元素列表,我需要搜索具有文本“UserName”的特定类型的元素。我在“UserName”文本后面还有一个数字,所以它们看起来像这样:

I need to find each UserName element in this list but since each one is different due to the number at the end of each one's name I haven't been able to find a way to do this. What i was hoping for was a wildcard or something but that's not working for me.

我需要在此列表中找到每个UserName元素,但由于每个名称末尾的数字不同,因此我无法找到执行此操作的方法。我所希望的是一个通配符或其他东西,但这对我不起作用。

Any help would be appreciated.

任何帮助,将不胜感激。

<Profile>
   <Roles23></Roles>
   .
   .
   .
   <Rolese14></Roles>
   .
   .
   <Roles06></Roles>

   etc
   .

 </Profile>

3 个解决方案

#1


Please take 15 minutes to understand LINQ to XML! It will take care of such needs easily. If you are not using .NET then take a look at XPATH.

请花15分钟了解LINQ to XML!它将轻松地处理这些需求。如果您不使用.NET,请查看XPATH。

#2


Using XML like this:

像这样使用XML:

<root>
    <user1></user1>
    <user2></user2>
    <user3></user3>
</root>

This XPATH expression will work: /root/*[starts-with(name(), 'user')]

这个XPATH表达式将起作用:/ root / * [starts-with(name(),'user')]

#3


Given the poor XML code you provided, it's really difficult to give an answer. Please read up on XPath, the answer you are looking for can certain be found on these two pages:

鉴于您提供的XML代码很差,很难给出答案。请阅读XPath,您可以在以下两页找到您正在寻找的答案:

http://www.w3schools.com/XPath/xpath_syntax.asp

http://www.w3schools.com/XPath/xpath_functions.asp

#1


Please take 15 minutes to understand LINQ to XML! It will take care of such needs easily. If you are not using .NET then take a look at XPATH.

请花15分钟了解LINQ to XML!它将轻松地处理这些需求。如果您不使用.NET,请查看XPATH。

#2


Using XML like this:

像这样使用XML:

<root>
    <user1></user1>
    <user2></user2>
    <user3></user3>
</root>

This XPATH expression will work: /root/*[starts-with(name(), 'user')]

这个XPATH表达式将起作用:/ root / * [starts-with(name(),'user')]

#3


Given the poor XML code you provided, it's really difficult to give an answer. Please read up on XPath, the answer you are looking for can certain be found on these two pages:

鉴于您提供的XML代码很差,很难给出答案。请阅读XPath,您可以在以下两页找到您正在寻找的答案:

http://www.w3schools.com/XPath/xpath_syntax.asp

http://www.w3schools.com/XPath/xpath_functions.asp