读书人

关于返回数组有关问题

发布时间: 2014-01-17 00:06:00 作者: rapoo

关于返回数组问题
做一个读取XML配置的方法,在取用户名(mUser = xObj.mValue)和密码(mPassWord = xObj.mValue)时,为什么返回的数组是最后一次调用的值,既mUser随着mPassWord的改变而改变,不知道这是为什么,有什么方法可以实现,请高手指教,万分感谢!

XML格式
<root>
<IdNum>2</IdNum>
<Account>
<user>
<id>sunzhenggo</id>
<password>123456</password>
</user>
<user>
<id>mengmeng</id>
<password>654321</password>
</user>
</Account>
</root>

Form类代码


private const string ACC_PATH = "day\\AccName.xml";
private const string USER_NODE = "root/Account/user";
private void InitData()
{
int Respond = 0;
xObj = new XmlFile();
if ((Respond = xObj.ReadXML(ACC_PATH, USER_NODE, "id")) == 0)
{
mUser = xObj.mValue;
}
if ((Respond = xObj.ReadXML(ACC_PATH, USER_NODE, "password")) == 0)
{
mPassWord = xObj.mValue;
}
}



XmlFile类代码

public class XmlFile : XmlDocument
{
int integer;
string[] mStr1 = new string[5];
public string[] mValue = new string[5];

public int ReadXML(string mPath,string mName,string mChild)
{
string mStr="";
int i = 0;
try
{
this.Load(mPath);
XmlNode node = this.SelectSingleNode(mName);
XmlNodeList list = this.SelectNodes(mName);
if (node != null)
{
foreach (XmlNode item in list)
{
XmlNode xNode1 = item.SelectSingleNode(mChild);
mStr1[i] = xNode1.InnerText;
mValue[i] = mStr1[i];
i++;
}
}
node = null;
list = null;
return 0;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return -1;


}
}



[解决办法]
普通的xml读取方法

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("XMLFile.xml");
XmlNode root = xmlDoc.SelectSingleNode("root");
int numberOfAccount = int.Parse(root.SelectSingleNode("IdNum").InnerText);
XmlNodeList nodes = root.SelectSingleNode("Account").ChildNodes;

UserInfo[] users = new UserInfo[numberOfAccount];
for (int i = 0; i < numberOfAccount; i++)
{
XmlNode elm = nodes[i];
UserInfo user = new UserInfo(){ id = elm["id"].InnerText,password = elm["password"].InnerText };
users[i] = user;
}

class UserInfo
{
public string id { get; set; }
public string password { get; set; }
}

[解决办法]
           string xml = @"<root>
<IdNum>2</IdNum>
<Account>
<user>
<id>sunzhenggo</id>
<password>123456</password>
</user>
<user>
<id>mengmeng</id>
<password>654321</password>
</user>
</Account>
</root>";

XmlDocument xdoc1 = new XmlDocument();
xdoc1.LoadXml(xml);
XmlNodeList lists= xdoc1.SelectNodes("root/Account/user");

Dictionary<string, string> dictUsers = new Dictionary<string, string>();

foreach (XmlNode x in lists)
{
if (x!=null)
{
string key = x.SelectSingleNode("id").InnerText;
string value = x.SelectSingleNode("password").InnerText;
dictUsers.Add(key, value);


}
}

读书人网 >C#

热点推荐