Is there a way to replace the whole XML node at once?

I need to replace the product list (UserCart) with an updated product list for the specified user. How can I do this without calling each property?

<Users>
<UserInfo>
  <Name>ddd</Name>
  <Wallet>0</Wallet>
  <UserCart>
    <Products_>
      <MedicineProduct
        Product_Name="sak"
        Product_ID="0"
        Price="0"
        Quntity="0"
        Image="" />
    </Products_>
  </UserCart>
</UserInfo>

Here where I am stuck ...

public static void Edit(UserInfo user, Products usercart)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(path);
    XmlNode node = doc.SelectSingleNode(string.Format("//UserInfo[./Name/text()='{0}']", user.Name));
}

The specified user was found. How to replace the entire UserCart node with a new value?

+4
source share
2 answers

You can use the new XDocumentXML API and its method XElement.ReplaceWith().

var xml = "<Users><UserInfo><Name>Old Name</Name></UserInfo></Users>";
var document = XDocument.Parse(xml);
var replacedNode = document.Descendants("UserInfo")
                           .SingleOrDefault(x => x.Descendants("Name")
                                                  .Single()
                                                  .Value == "Old Name");

// The code below uses C# 6.0 null propagation feature to handle 
// the case when replacedNode is null (not found in XML).
// In case you use C# 5.x or lower, you can just check it in an IF statement
replacedNode?.ReplaceWith(new XElement("UserInfo", 
                                       new XElement("Name", "New Name")));

Console.WriteLine(document.ToString());

UPDATE (01/14/2016)

, . , - ( ) / (). , - XML, , .

public static class XmlExtensions
{
    public static XElement ToXElement(this object obj)
    {
        using (var memoryStream = new MemoryStream())
        {
            using (TextWriter streamWriter = new StreamWriter(memoryStream))
            {
                var xmlSerializer = new XmlSerializer(obj.GetType());
                xmlSerializer.Serialize(streamWriter, obj);
                return XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        var xml = "<Users><UserInfo><Name>Old Name</Name><UserCart></UserCart></UserInfo></Users>";

        var document = XDocument.Parse(xml);

        var userCart = document.Descendants("UserInfo")
            .SingleOrDefault(x => x.Descendants("Name").Single().Value == "Old Name")
            ?.Element("UserCart");

        var newUserCart = new UserCart
        {
            Products = new List<Product>
            {
                new Product { Name = "First" },
                new Product { Name = "Second" }
            }
        };

        userCart?.ReplaceWith(newUserCart.ToXElement());

        Console.WriteLine(document.ToString());
    }
}

public class UserCart
{
    public List<Product> Products { get; set; } 
}

public class Product
{
    public string Name { get; set; }
    public int Quantity { get; set; }
}

, System.Xml (, XmlElement) . , XmlSerializer . , .

+2

, . - , :

XmlNode cart = doc.SelectSingleNode(string.Format("//UserInfo[./Name/text()='{0}']/UserCart", "ddd"));
cart.InnerText = "Replaced!";

. , node .

XML, , :

XmlNode cart = doc.SelectSingleNode(string.Format("//UserInfo[./Name/text()='{0}']/UserCart", "ddd"));
 // clear out nodes
cart.RemoveAll();
cart.AppendChild(doc.CreateNode(XmlNodeType.Element, "test", ""));

, API XDocument, ...

XDocument doc = XDocument.Parse(xml);
//doc.LoadXml(xml);

XElement cart = doc.Root.Descendants("UserCart").Where(x => (string)x.Parent.Element("Name") == "ddd").FirstOrDefault();
if (cart != null)
    cart.ReplaceNodes(new XElement("test")); // or you can do cart.Value = "text" you're not adding new elements.
0

Source: https://habr.com/ru/post/1624305/


All Articles