Find XmlNode where attribute value is contained in string

三世轮回 提交于 2019-12-11 01:51:18

问题


I have an xml file...

<?xml version="1.0" encoding="UTF-8"?>
<items defaultNode="1">
    <default contentPlaceholderName="pageContent" template="" genericContentItemName="" />
    <item urlSearchPattern="connections-learning" contentPlaceholderName="pageContent" template="Connections Learning Content Page" genericContentItemName="" />
    <item urlSearchPattern="online-high-school" contentPlaceholderName="pageContent" template="" genericContentItemName="" />
</items>

I am trying to find the first node where the urlSearchPattern attribute is contained in the string urlSearchPattern. Where I'm having trouble is finding the nodes where the attribute is contained in the string value instead of the string value be contained in the attribute.

Here's my attempt so far. This will find the firstOrDefault node where the string value is contained in the attribute (I need the opposite)...

string urlSearchPattern = Request.QueryString["aspxerrorpath"];
MissingPageSettingsXmlDocument missingPageSettingsXmlDocument = new MissingPageSettingsXmlDocument();
XmlNode missingPageItem = missingPageSettingsXmlDocument.SelectNodes(ITEM_XML_PATH).Cast<XmlNode>().Where(item => item.Attributes["urlSearchPattern"].ToString().ToLower().Contains(urlSearchPattern)).FirstOrDefault();

回答1:


well... then invert !

var result = missingPageSettingsXmlDocument
                .SelectNodes(ITEM_XML_PATH)
                .Cast<XmlNode>()
                .FirstOrDefault(
                    m => m.Attributes != null && 
                    m.Attributes["urlSearchPattern"] != null && 
                    urlSearchPattern.Contains(m.Attributes["urlSearchPattern"].ToString().ToLower())
                 );



回答2:


Using this Xml Library, and providing your ITEM_XML_PATH looks something like: //item

XElement root = XElement.Load(file); // or .Parse(string)
var matches = root.XPath("//item[contains({0}, {1}, false)]", 
    urlSearchPattern, new NodeSet("@urlSearchPattern"));

false for converting all values with .ToLower() and reversed pattern with the nodeset, it will do the search of pattern.Contains(nodeset).

If you have items without a urlSearchPattern or their value is "", you can add and . != '' to the xpath expression to remove them from the result.

The library is in its infancy, so if your ITEM_XML_PATH is real complicated this might not work for you.

Update: Based on Pawel's comments, using the included Linq-to-Xml XPath version:

root.XPathSelectElements(
    "//item[contains('" + urlSearchPattern + "', @urlSearchPattern)]");


来源:https://stackoverflow.com/questions/11263523/find-xmlnode-where-attribute-value-is-contained-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!