简体   繁体   中英

How to change attribute type <TRUE/FALSE> in xml using c#

I have to change xml attribute value for 'Hierarchy_RestrictedOperations' toTRUE to FALSE. Here, the xml looks like

    <BusinessRules>
    <BusinessRule>
        <Type>All_NoEmptyRequiredProperty</Type>
        <Enabled ptype="BOOLEAN">TRUE</Enabled>
    </BusinessRule>
    <BusinessRule>
        <Type>All_CheckStringLength</Type>
        <Enabled ptype="BOOLEAN">TRUE</Enabled>
    </BusinessRule>
    <BusinessRule>
<BusinessRule>
    <Type>Hierarchy_RestrictedOperations</Type>
    <Enabled ptype="BOOLEAN">TRUE</Enabled>
</BusinessRule> 
<BusinessRule>
  <Type>ProdOff_AllowAccountPOCurrencyMismatch</Type>
  <Enabled ptype="BOOLEAN">FALSE</Enabled>
</BusinessRule>
<!-- Following business rule was added for FEAT-147 -->
<BusinessRule>
  <Type>ProdOff_AllowMultiplePISubscriptionRCNRC</Type>
  <Enabled ptype="BOOLEAN">FALSE</Enabled>
</BusinessRule>
<!-- Following business rule was added for CORE-10776 -->
<BusinessRule>
  <Type>ImmediateSubscriptionTermination</Type>
  <Enabled ptype="BOOLEAN">FALSE</Enabled>
</BusinessRule>

Can anybody help me using c# I tried with below code

     XmlDocument xml = new XmlDocument();
  xml.Load("R:\\config\\ProductCatalog\\PCConfig.xml");


  XmlNodeList nodes = xml.SelectNodes("//BusinessRule");
  //XmlNodeList type = xml.SelectNodes("//Hierarchy_RestrictedOperations");
  foreach (XmlElement element in nodes)
    {

      element.SelectSingleNode("Type").InnerText = "Hierarchy_RestrictedOperations";

    }
    xml.Save("R:\\config\\ProductCatalog\\PCConfig.xml");

You can do it something like this

XDocument xdc = XDocument.Load(YourXMLFile);
xdc.Descendants("BusinessRule")
   .LastOrDefault()
   .Descendants("Enabled")
   .FirstOrDefault()
   .Value = "False";
xdc.Save(YourXMLFile);

or

XDocument xdc = XDocument.Load(YourXMLFile);    
xdc.Descendants("BusinessRule")
   .Where(x => x.Descendants("Type")
                .FirstOrDefault()
                .Value == "Hierarchy_RestrictedOperations"
          )
   .Descendants("Enabled")
   .FirstOrDefault()
   .Value = "False";

Try this:

XElement element = xml.Root.Elements("BusinessRule").Where(xElement => xElement.Element("Type").Value == "Hierarchy_RestrictedOperations").FirstOrDefault();

        if(element != null)
        {
            element.Element("Enabled").Value = "FALSE";
        }

        xml.Save("R:\\config\\ProductCatalog\\PCConfig.xml");

Make sure that the tags of the xml file are all correct. Hope this was useful.

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