【问题标题】:Read other xml elements based on the root node and one of the element?根据根节点和元素之一读取其他 xml 元素?
【发布时间】:2011-12-10 10:58:56
【问题描述】:

我的 XML 如下所示。

<UrlRoutes>
  <ActivityPR>
     <Source>activity/editactivity</Source>
     <DestinationController>Activity</DestinationController>
     <DestinationAction>Editactivity</DestinationAction>  
  </ActivityPR>
  <UserSettings>
     <Source>settings/subscriptions</Source>
     <DestinationController>UserSettings</DestinationController>
     <DestinationAction>GetUserPreferenceSettings</DestinationAction>
  </UserSettings>
</UrlRoutes>

我将在 var 中拥有 Source 元素值,比如 sourceX 。前

SourceX = "settings/subscriptions" 

SourceX = "activity/editactivity"

我正在尝试使用以下代码获取父节点,如果有问题请告诉我

XmlElement xmlNode = xmlDoc.GetElementById(SourceX);
XmlNode parent = xmlNode.ParentNode;

现在对于父节点(比如ActivityPRUsersettings)和Source的组合,我必须找到对应的DestinationControllerDestinationAction

我该怎么做?更喜欢传统的 XML 而不是 LINQ,因为其余的代码都是这种形式。

if(node!=null)
        {
            XmlElement routeElement = (XmlElement)node;


            strController = routeElement.GetElementsByTagName("DestinationController")[0].InnerText.ToString();
            strAction = routeElement.GetElementsByTagName("DestinationAction")[0].InnerText.ToString();


        }

【问题讨论】:

    标签: xml asp.net-mvc-3 xmlnode


    【解决方案1】:

    我假设您已经将 XML 加载到您的 XmlDocument 中 - 对吗?

    在这种情况下,你应该可以使用这样的东西:

    string xpath = string.Format("/UrlRoutes/*[Source='{0}']", sourceX);
    XmlNode node = xmlDoc.SelectSingleNode(xpath);
    
    if(node != null)
    {
        // use the node to do whatever you need to do
    }
    

    xpath 表达式基本上选择/UrlRoutes 下包含&lt;Source&gt; 元素并将给定字符串作为其值的任何节点。这意味着:&lt;Source&gt; 的值必须是唯一的。

    更新:如果您知道您只想在节点 &lt;UserSettings&gt; 内搜索,您可以使您的 XPath 表达式更具选择性:

    string parentNode = "UserSettings";
    string sourceX = "settings/subscriptions";
    
    string xpath = string.Format("/UrlRoutes/{0}[Source='{1}']", parentNode, sourceX);
    

    但是使用这种更具选择性的 XPath,当您的示例中有 sourceX = "activity/editactivity" 时,您将 能够找到一个节点(因为这是 not 在 @ 987654329@节点)

    更新 #2:我可能会使用此代码来获取节点内的元素:

    if(node != null)
    {
       string dc = node.SelectSingleNode("DestinationController").InnerXml;
       string da = node.SelectSingleNode("DestinationAction").InnerXml;
    }
    

    这样,您无需先转换为XmlElement

    【讨论】:

    • 谢谢 Marc,xml 似乎是这样一种方式,即 xml 中可能有多个 UserSettings 节点,但 UserSettings 和 source 的组合将是唯一的,我认为我需要搜索这2项(父节点和SourceX)的组合,我不知道你的代码是否在那里工作,是吗?
    • @AdarshK:只要 source 的值在整个 XML 文档中是唯一的 - 那么我的代码就可以正常工作。
    • 哦,仪式,来源似乎是唯一的,因此我相信您的原始代码可以工作,对吧?
    • @AdarshK: 是的,如果 &lt;Source&gt; 是唯一的 - 那么你可以使用我的第一个 XPath 表达式
    • 我在我的问题末尾添加了一个代码,你能确认它是否有效吗?
    猜你喜欢
    • 1970-01-01
    • 2013-08-23
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多