如何在Windows 8 Metro风格上更新xml文件的节点?

时间:2013-01-03 22:34:55

标签: c# windows-8 microsoft-metro

我将在我的xml文件中向父节点添加一个新节点。此代码的单元测试表示“成功”,它正在传递,但在xml中没有添加节点。

另外,一些测试我得到了错误; <<访问被拒绝。 (HRESULT异常:0x80070005(E_ACCESSDENIED))>> 在SaveToFileAsync

我有什么问题?还有另一种方法可以做到这一点吗?

    public string ConnectionPath { get; set; }
    protected string XPath { get; set; }
    protected string XParentPath { get; set; }
    protected XmlDocument Source { get; set; }
    protected StorageFolder SFolder { get; set; }
    protected StorageFile SFile { get; set; }

    public RepositoryBase(string connectionPath)
    {
        this.ConnectionPath = connectionPath;
    }

     public async void Insert(T entity)
     {
        SFolder = Package.Current.InstalledLocation;
        SFile = await SFolder.GetFileAsync(this.ConnectionPath);
        var content = await FileIO.ReadTextAsync(SFile);
        if (!string.IsNullOrEmpty(content))
        {
            Source = new XmlDocument();
            Source.LoadXml(content);
        }
        var tagName = typeof(T).Name;
        if (tagName != null)
        {
            IXmlNode parentNode = Source.SelectSingleNode(XParentPath);
            if (parentNode != null)
            {
                XmlElement newNode = Source.CreateElement(tagName);
                newNode.InnerText = GetContent(entity);
                parentNode.AppendChild(newNode);
            }              
        }        
        await Source.SaveToFileAsync(SFile);
     }

* PlaceRepositoryClass;

    public class PlaceRepository : RepositoryBase<Place>
    {
        public PlaceRepository()
        : base("Data\\bla\\bla.xml")
        {

             XPath = "/Country[Id=1]/Cities/City[Id=1]/Places/Place";
             XParentPath = "/Country[Id=1]/Cities/City[Id=1]/Places";
         }
     }
  • 单元测试方法;

    [TestMethod]
    public void AppendNode()
    {
        Place place = new Place()
        {
            Id = 40,
            Name = "xxxxx",
            SummaryPath = "yyyyy",
            Logo = "xy.png",
            LogoSmall = "xy_small.png",
            Latitude = "32.423",
            Longitude = "34.23424",
            Content = new PlaceContent() { Items = new List<ContentItem>() { new ContentItem() { TextPath = "aaaa", Header = "bbbbb", AudioFilePath = "x.mp3" } } },
            Gallery = new PhotoGallery() { Photos = new List<Photo>() { new Photo() { Path = "ab.png", Text = "abab" } } }
        };
    
        PlaceRepository repository = new PlaceRepository();
        repository.Insert(place);
    }
    

1 个答案:

答案 0 :(得分:1)

您正在尝试写入属于应用程序包的文件,这是只读的。您可以将文件复制到本地存储并在那里进行修改。