0

该应用程序应不时将节点添加到Goals.xml文件中。所以它的dynamic. 添加节点的代码:

XmlWriterSettings settings=new XmlWriterSettings();  
settings.OmitXmlDeclaration= true;
settings.Indent = true;
settings.IndentChars = ("\t");

using (IsolatedStorageFile myIsolatedStorage = 
    IsolatedStorageFile.GetUserStoreForApplication())
using (IsolatedStorageFileStream stream = 
    myIsolatedStorage.OpenFile("Goals.xml", FileMode.Append))
{
    XmlSerializer serializer = new XmlSerializer(typeof(List<Goals>));
    using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings))
    {
        serializer.Serialize(
            xmlWriter, 
            GenerateGoalsData(name, description, progress));
    }
}

private List<Goals> GenerateGoalsData(
    string name, 
    string description, 
    string progress)
{
    List<Goals> data = new List<Goals>();
    data.Add(new Goals() { 
            Name=name, 
            Description=description, 
            Progress=progress});
    return data;
}

我也有课Goals。但它会产生不好的XML

<ArrayOfGoals xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Goals>
        <Name>Jack</Name>
        <Description>lalala</Description>
        <Progress>97</Progress>
    </Goals>
</ArrayOfGoals>
<ArrayOfGoals xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Goals>
        <Name>Taaaaaa</Name>
        <Description>nanana</Description>
        <Progress>50</Progress>
    </Goals>
</ArrayOfGoals>

如何去除XML重复:

</ArrayOfGoals>
<ArrayOfGoals xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">

所以XML看起来像这样:

<ArrayOfGoals xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Goals>
        <Name>Jack</Name>
        <Description>lalala</Description>
        <Progress>97</Progress>
    </Goals>
    <Goals>
        <Name>Taaaaaa</Name>
        <Description>nanana</Description>
        <Progress>50</Progress>
    </Goals>
</ArrayOfGoals>

或者如何在不自动添加该字符串的情况下附加节点?

4

3 回答 3

2

反序列化您的数据,添加新值并进行序列化。但是使用FileMode.Create 而不是FileMode.Append

于 2012-09-09T17:23:05.150 回答
2

生成的文件是无效的 XML,因此您将无法直接将其用作有效的 Xml 进行反序列化。

但它实际上是可以使用标准类读取的有效“Xml 片段”:当在 XmlReader.Create 调用的 XmlReaderSettings 中指定 ConformanceLevel.Frament 时,XmlReader 可以读取片段。我认为您甚至可以直接从此类阅读器中反序列化类(不确定)。

旁注:读取旧数据,附加您需要的内容并作为整个文件序列化回来会更容易(但问题和错误更少)。

于 2012-09-09T17:39:27.527 回答
0
XmlRootAttribute root = new XmlRootAttribute("Goals");     
XmlSerializer serializer = new XmlSerializer(typeof(List<Goals>), root);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);   
using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings))
{
    serializer.Serialize(xmlWriter, GenerateGoalsData(name, description, progress), ns)
}
于 2017-08-17T19:47:09.753 回答