【问题标题】:How I can remove special XElements in a XML file in C#?如何在 C# 中删除 XML 文件中的特殊 XElement?
【发布时间】:2013-10-19 11:31:21
【问题描述】:

您好,我对 xaml 和 xdocument 的工作有疑问。

致我的应用:

我有一个 DropDownList 控件,我希望它填充一个 xml 文件,但我希望用户只能看到特殊值。我的意思是他必须在一个活动目录组中。所以我想在我的代码中加载 xml 并使用过滤器值更新它并将其加载到下拉列表中。

这里是我的 xml:

<plants>
  <plant id="DB" display=".testDB.." group="NPS_DB" />
  <plant id="EL" display=".testEL.." group="NPS_EL" />
  <plant id="IN" display="..testIN." group="NPS_IN" />
  <plant id="SB" display=".testSB.." group="NPS_SB" />
  <plant id="BL" display=".testBL.." group="NPS_BL" />
  <plant id="LS" display="..testLS.." group="NPS_LS" />
</plants>

这是我的代码:

ArrayList ActiveUserList = MyClass.GetGroupmemberList(DOMAIN, Username);

            XDocument x = XDocument.Load(Server.MapPath(@"~\App_Data\location.xml"));

            int index = ActiveUserList.Count;

            ArrayList DropDownList = new ArrayList();

            for (int i = 0; i < index; i++)
            {
                IEnumerable<XElement> att = from el in x.Descendants("plant")
                                            where (string)el.Attribute("group") == ActiveUserList[i].ToString()
                                            select el;

                //????
            }

如何使用找到的 Xelements 更新 xml 并使用它创建一个新的 xml 并将其加载到我的下拉列表中。

如果我的用户名在组 nps_db 和 nps_el 中,我希望只看到 ths:

<plants>
      <plant id="DB" display=".testDB.." group="NPS_DB" />
      <plant id="EL" display=".testEL.." group="NPS_EL" />
 </plants>

【问题讨论】:

    标签: c# asp.net xml arraylist linq-to-xml


    【解决方案1】:

    我没有获取匹配列表,而是删除了不匹配列表。以这种方式获取所需的 XML 作为输出似乎更直接。

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/xml";
    
        string xml = @"
            <plants>
              <plant id=""DB"" display="".testDB.."" group=""NPS_DB"" />
              <plant id=""EL"" display="".testEL.."" group=""NPS_EL"" />
              <plant id=""IN"" display=""..testIN."" group=""NPS_IN"" />
              <plant id=""SB"" display="".testSB.."" group=""NPS_SB"" />
              <plant id=""BL"" display="".testBL.."" group=""NPS_BL"" />
              <plant id=""LS"" display=""..testLS.."" group=""NPS_LS"" />
            </plants>
        ";
    
        XDocument x = XDocument.Parse(xml);
        string[] ActiveUserList = { "NPS_DB", "NPS_BL" };
    
        var att = x.Descendants("plant").Where(el => !ActiveUserList.Contains(el.Attribute("group").Value));
    
        att.Remove();
    
        context.Response.Write(x.ToString());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多