XmlReader - I need to edit an element and produce a new one

前端 未结 5 2111
花落未央
花落未央 2020-12-20 15:54

I am overriding a method which has an XmlReader being passed in, I need to find a specific element, add an attribute and then either create a new XmlReader or just replace t

5条回答
  •  时光取名叫无心
    2020-12-20 16:37

    I would rather prefer to load the xml into XmlDocument object and use Attributes collection to modify the value and call Save method to update this value. Below code works for me.

     public static void WriteElementValue ( string sName, string element, string value)
     {
      try
      {
        var node = String.Format("//elements/element[@name='{0}']", sName);
        var doc = new XmlDocument { PreserveWhitespace = true };
        doc.Load(configurationFileName);
    
        var nodeObject = doc.SelectSingleNode(node);
    
         if (nodeObject == null)
             throw new XmlException(String.Format("{0} path does not found any matching 
             node", node));
    
        var elementObject = nodeObject[element];
    
        if (elementObject != null)
        {
           elementObject.Attributes["value"].Value = value;
        }
    
        doc.Save(configurationFileName);
    }
    catch (Exception ex)
    {
       throw new ExitLevelException(ex, false);
    }
    

    }

    I've also observed when you use XmlWriter or XmlSerializer the whitespaces were not correctly preserved, this could be annoying sometimes

提交回复
热议问题