简体   繁体   中英

How I can remove special XElements in a XML file in C#?

hi I have a question to xaml and the work with xdocument.

To My Appication:

I have a DropDownList Control and I want it fill with a xml file but i want that a user can only see special values. I mean thart he must be in a active directory group. So I want to load the xml in my code and update this with filter values and load it to the dropdown.

here my 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>

here my code:

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;

                //????
            }

How I can update the xml with the found Xelements and create a new xml with this and load it to my dropdownlist.

I want if my username is in the group nps_db and nps_el see only ths:

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

Instead of getting the list of matches, I removed the list of non-matches. Seemed more direct to get the XML you want as the output that way.

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM