简体   繁体   中英

WP8 create xml file c#

I am trying to create xml file like below

        <IMEI>ABCD</IMEI>
        <Manufacturer>Nokia</Manufacturer>
        <Model>Lumia 525</Model>
        <Items>
           <Item>
                <Name>Contact</Name>
                <Size>
                    <Value>123</Value>
                    <Type>KB</Type>
                </Size>
                <MD5>78sd8f6sd6fsdf8sdbs5f78svbfsd576s</ MD5>
                <Desc>Contact is added</ Desc >
           </Item>
        </Items>

I have tried something like this

doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"));

doc.Add(new XElement(("IMEI"), "ABCD"));
doc.Add(new XElement("Manufacturer"), "Nokia");
doc.Add(new XElement("Model"), "Lumia 525");
var contactsElement = new XElement("Item",
                        new XElement("Name", "Contact"),
                        new XElement("Size",
                            new XElement("Value", "123"),
                            new XElement("Type", "KB")),
                       new XElement("MD5", "78sd8f6sd6fsdf8sdbs5f78svbfsd576s"),
                       new XElement("Desc", "Contact File"));
var mainNode = new XElement("Items", new XElement(contactsElement));
doc.Root.Add(mainNode);

But not getting correct file. I also want to append new Item in Items node. How can I append when I get new item?

  1. Your XML is invalid as posted. It should have single root element to be a valid XML.
  2. The way your code adds new element is wrong. It will add two nodes instead of one : one empty xml element node, and a text node.

You can try this way to generate correctly formatted XML :

doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
                                        new XElement("Root"));
doc.Root.Add(new XElement("IMEI", "ABCD"));
doc.Root.Add(new XElement("Manufacturer", "Nokia"));
doc.Root.Add(new XElement("Model", "Lumia 525"));
var contactsElement = new XElement("Item",
                                    new XElement("Name", "Contact"),
                                    new XElement("Size",
                                        new XElement("Value", "123"),
                                        new XElement("Type", "KB")),
                                    new XElement("MD5", "78sd8f6sd6fsdf8sdbs5f78svbfsd576s"),
                                    new XElement("Desc", "Contact File"));
var mainNode = new XElement("Items", new XElement(contactsElement));
doc.Root.Add(mainNode);

And for adding new Item within Items element later :

//get existing <Items> element
var items = doc.Root.Element("Items");
//add new <Item> to <Items>
items.Add(XElement.Parse(newContactsElement));
//then save the XDocument back replacing previously saved XML

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