Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

Monday, March 15, 2010

how to append to an xml file with XDocument and XElement

            XDocument xDoc = XDocument.Load(_filePath);
            XElement root = xDoc.Root;

            root.Add(new XElement("MenuItem",
                new XElement("Name", "ttttt"),
                new XElement("Url", "www.this.com"),
                new XElement("Images",
                    new XElement("image", "img1"),
                    new XElement("image", "img2")
                    )
                )
            );

            root.Save(_filePath);


<?xml version="1.0" encoding="utf-8"?>
<MenuItems>
  <MenuItem>
    <Name>rrrrrr</Name>
    <Url>www.this1.com</Url>
    <Images>
    <image>img1</image>
    <image>img2</image>
    </Images>
  </MenuItem>
  <MenuItem>
    <Name>ttttt</Name>
    <Url>www.this.com</Url>
    <Images>
      <image>img1</image>
      <image>img2</image>
    </Images>
  </MenuItem>
</MenuItems>

Saturday, March 6, 2010

aspx linq get all unique items from an xml

        XDocument xDoc = XDocument.Load(Server.MapPath("App_Data/MyCollections.xml"));
        List <string>productTypes =
            xDoc.Descendants("CollectionItem")
            .SelectMany(ci => ci.Descendants("ProductType"))
            .Select(pt => pt.Value).Distinct().ToList();


this will return a List<> with all the Distinct ProductType Values under the CollectionItem node of the xml file.
.SelectMany because we want all of the values for ProductType
.Select says we want the Value of the node and only want Distinct ones.