Skip to main content
 首页 » 编程设计

c#之Windows Phone 8 中格式错误的 XML

2024年02月13日13yjmyzz

经过几个小时的折腾,我终于得到了 WP8 来写入 xml 文件...比我原先想象的要简单。

但是,现在生成的文档的结构并不符合预期。

XDocument tagRegistry = new XDocument(new XElement("SmartSafe")); 
 
        if (stringUid == "" | desiredName == "" | latitude == "" | longitude == "" | stringUid == null | desiredName == null | latitude == null | longitude == null) 
        { 
            MessageBox.Show("Something went wrong....Please try again in a moment..."); 
        } 
        else 
        { 
            tagRegistry.Element("SmartSafe").Add(new XElement("Tag",  
                new XAttribute("tag", stringUid),  
                new XAttribute("name", desiredName),  
                new XAttribute("latitude", latitude),  
                new XAttribute("longitude", longitude))); 
        } 
        using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) 
        { 
            using (Stream stream = storage.CreateFile("/tagRegistry.xml")) 
            { 
                tagRegistry.Save(stream); 
            } 
        } 

这会生成以下 XML 文件。

    <?xml version="1.0" encoding="utf-8"?> 
    <SmartSafe> 
      <Tag tag="2" name="Home" latitude="53.8975533333333" longitude="-1.94872666666667" /> 
    </SmartSafe> 

我的意图是:

<?xml version="1.0" encoding="utf-8"?> 
<SmartSafe> 
  <Tag> 
    <tag>2<tag> 
    <name>Home</name> 
    <latitude>12345<latitude> 
    <longitude>12345<longitude/> 
  </Tag> 
</SmartSafe> 

如何更改我的代码以正确生成文件?

请您参考如下方法:

它完全按照您的指示去做。您正在为元素创建属性

使用 XElement 而不是 XAttribute。