我正在尝试读取XML文件,但是当我读取它时,它只会获取我的Group元素的最后一个值,而不是在每个Group的trylement break中设置Group的text属性。所有帮助表示赞赏。
public static void ReadFile()
{
string MyText = string.Empty;
string Notes = string.Empty;
string UserName = string.Empty;
string Password = string.Empty;
string Url = string.Empty;
string Title = string.Empty;
string MyGroup = string.Empty;
Group group = new Group("Hello", 0);
XmlTextReader xmlReader = new XmlTextReader("C:/KeyText.xml");
while (xmlReader.Read()) // Read nodes sequentially
{
if (xmlReader.Name == "Group" & xmlReader.NodeType.ToString() == "EndElement")
{
group.Text = MyText;
AddGroupXML(group);
}
if (xmlReader.NodeType == XmlNodeType.Element)
{
if (xmlReader.LocalName == "Text")
{
MyText = xmlReader.ReadString();
}
if (xmlReader.LocalName == "Notes")
{
Notes = xmlReader.ReadString();
}
if (xmlReader.LocalName == "UserName")
{
UserName = xmlReader.ReadString();
}
if (xmlReader.LocalName == "Password")
{
Password = xmlReader.ReadString();
}
if (xmlReader.LocalName == "Url")
{
Url = xmlReader.ReadString();
}
if (xmlReader.LocalName == "Title")
{
Title = xmlReader.ReadString();
}
}
if (xmlReader.Name == "Key" & xmlReader.NodeType.ToString() == "EndElement")
{
Key MyKey = new Key();
MyKey.Notes = Notes;
MyKey.Title = Title;
MyKey.UserName = UserName;
MyKey.Url = Url;
MyKey.Password = Password;
group.Keys.Add(MyKey);
}
}
xmlReader.Close();
GroupsRead.Invoke();
}
XML:
<?xml version="1.0"?>
<Groups>
<Group>
<ImageIndex>0</ImageIndex>
<Text>wcwpgcuotlx</Text>
<Keys>
<Dog/>
<Key>
<Notes>4ktaiyduner</Notes>
<Password>0y2cg1kodre</Password>
<Title>a2yj4biqd5u</Title>
<Url>de2uym5vyg1</Url>
<UserName>ogcl3uyvy2r</UserName>
</Key>
<Key>
<Notes>3dmchyaqcvt</Notes>
<Password>lbgfralkng4</Password>
<Title>fnha4ienzua</Title>
<Url>n3pmk5elaso</Url>
<UserName>njk55ov4eef</UserName>
</Key>
</Keys>
</Group>
<Group>
<ImageIndex>0</ImageIndex>
<Text>vrmijzokft2</Text>
<Keys>
<Dog/>
</Keys>
</Group>
</Groups>
答案 0 :(得分:0)
我认为你的问题是你有一个Group
对象用于所有组。因此,由于每次使用相同的参数调用AddGroupXML()
,结果将多次包含相同的对象。文本值将是您为它设置的最后一个。
要解决此问题,请将添加组的代码更改为:
group.Text = MyText;
AddGroupXML(group);
group = new Group("Hello", 0);
将来,如果使用LINQ to XML来处理XML,可能会更容易。如果你使用它,你的代码会简单得多。 (这种方法的缺点是它将整个XML加载到内存中,这对于大型XML文件来说是一个坏主意。)