[英]Read XML File's certain value from Isolated Storage
Hi I use this code to save an xml file 嗨,我使用此代码保存xml文件
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("test.xml", FileMode.Create, myIsolatedStorage))
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
{
writer.WriteStartElement("t", "test", "urn:test");
writer.WriteStartElement("TestA", "");
writer.WriteString(lbTestA.Text);
writer.WriteEndElement();
writer.WriteStartElement("TestB", "");
writer.WriteString(lbTestB.Text);
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
}
}
}
And it created the right xml file checked with Isolated Storage Explorer for WP7, now I want to read only the values stored in the and Tags the only code I could use was this one 并且它创建了正确的xml文件,并用WP7的Isolated Storage Explorer检查了该文件,现在我只想读取存储在和标签中的值,唯一可以使用的代码就是这个
private void loadgame_Click(object sender, EventArgs e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("test.xml", FileMode.Open);
using (StreamReader reader = new StreamReader(isoFileStream))
{
lsScore.DataContext = reader.ReadToEnd();
}
}
}
But it just reads the whole xml file as it is just a text, any ideas ? 但是它只是读取整个xml文件,因为它只是一个文本,有什么想法吗?
The reader.ReadToEnd() reads the whole file to string. reader.ReadToEnd()将整个文件读取为字符串。 If you want it as XML you have to construct an XDocument, eg:
如果您希望将其作为XML,则必须构造一个XDocument,例如:
var doc = XDocument.Parse(reader.ReadToEnd());
then get the content you want from the XML document using LINQ. 然后使用LINQ从XML文档中获取所需的内容。
Code reading the xml file. 代码读取xml文件。 I used a seperator between the values and later used the .Split to seperate the values
我在值之间使用了分隔符,后来使用.Split来分隔值
private void loadtest_Click(object sender, EventArgs e)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
if (storage.FileExists("test.xml"))
{
IsolatedStorageFileStream fileStream = storage.OpenFile("test.xml", FileMode.Open, FileAccess.ReadWrite);
XDocument test = XDocument.Load(fileStream);
string score = test.Root.Value.ToString();
string[] scores = score.Split(',');
foreach (string s in scores)
{
lbTestAScore.Text= scores[0].ToString();
lbTestBScore.Text = scores[1].ToString();
}
The XML File XML文件
<?xml version="1.0" encoding="utf-8"?>
<test>
<TeamA>300</TeamA>
<Seperator>,</Seperator>
<TeamB>-200</TeamB>
</test>
The output from string score = test.Root.Value.ToString();
字符串
score = test.Root.Value.ToString();
的输出score = test.Root.Value.ToString();
is 300,-200 是300,-200
I think this sums it all up. 我认为这就是全部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.