在WP7中添加元素到xml文件?

时间:2010-11-03 00:02:21

标签: xml silverlight windows-phone-7

如何在wp7中向xml文件添加元素?我已经找到了很多来源,它们展示了如何在ASP.NET中添加元素,在浏览器上添加Silverlight等等。但在wp7上没有任何内容。我一直看到我们应该使用XDocument(XML to Linq),不知道从哪里开始。感谢。

2 个答案:

答案 0 :(得分:3)

WP7上的XDocument用法与silverlight相同。尝试这样的事情:

string xmlStr = "<RootNode><ChildNode>Hello</ChildNode></RootNode>";
XDocument document = XDocument.Parse(xmlStr);
document.Root.Add(new XElement("ChildNode", "World!"));
string newXmlStr = document.ToString(); 
// The value of newXmlStr is now: "<RootNode><ChildNode>Hello</ChildNode><ChildNode>World!</ChildNode></RootNode>"

答案 1 :(得分:1)

这就是我为WP7开发的方式:

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (var fs = store.OpenFile("MyXmlFile.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite))
    {
        var root = new XElement("Root");
        var someAttribute = new XAttribute("SomeAttribute", "Some Attribute Value");
        var child = new XElement("Child", "Child Value");
        var anotherChild = new XElement("AnotherChild", "Another Child Value");
        var xDoc = new XDocument();
        root.Add(someAttribute, child, anotherChild);
        xDoc.Add(root);
        xDoc.Save(fs);
    }
}