【问题标题】:LinQ to XML, selecting a node with 2 levels of search criteriaLinQ to XML,选择具有 2 级搜索条件的节点
【发布时间】:2020-12-06 08:47:33
【问题描述】:

我正在努力选择一个具有我想要修改的搜索条件的两层深的节点,我做错了什么? 我想我实际上是在寻找一种方法来在第一个查询下创建第二个“Where”级别以选择特定的子级别。

XML:

    <Model IDCode="ed385480-8905-4ddb-82b5-0eb9415b7676" Code="IGC">
    <Locations>
       <Location Type="Hub" Country="US" Office="NY" Contact="Frank"></Location>
       <Location Type="Satellite" Country="US" Office="LA" Contact="Sinatra"></Location>
    <Locations>
    </Model>
    <Model IDCode="ed385480-8905-4ddb-82b5-0eb9415b7676" Code="ABC">
    <Locations>
      <Location Type="Hub" Country="US" Office="NY" Contact="James"></Location>
      <Location Type="Satellite" Country="US" Office="LA" Contact="Franco"></Location>
    </Locations>
    </Model>

以及使用的代码;

    var locations= from IDCode in xdocConfig.Elements("Model")
                where IDCode != null && (IDCode.Attribute("IDCode").Value == Current.IDCode)
        select IDCode.Element("Locations");

        foreach (var location in locations)
        {
            if (location.Attribute("Office").Value == "LA")
            {
                location.SetAttributeValue("Office", "new value");
            }
        }
   }

【问题讨论】:

  • 使用:location.SetAttributeValue("Office", "new value");
  • 确实是到达那里的更好方法,我会更新,谢谢。到达节点进行更新是我的问题。

标签: c# xml linq


【解决方案1】:

注意:两种型号的 IDCode 相同。您可以将 Xml Linq 与字典一起使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, Dictionary<string, XElement>> dict = doc.Descendants("Model")
                .GroupBy(x => (string)x.Attribute("Code"), y => y.Descendants("Location")
                    .GroupBy(a => (string)a.Attribute("Office"), b => b)
                    .ToDictionary(a => a.Key, b => b.FirstOrDefault()))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            Dictionary<string, XElement> igc = dict["IGC"];
            XElement la = igc["LA"];
            la.SetAttributeValue("Office", "NY");

        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多