簡體   English   中英

讀取/寫入xml變量

[英]reading/writing variables to xml

我一直在尋找如何編寫服務器上注冊的每個播放器的詳細信息列表的方法,這樣,當人們登錄時,其詳細信息將從xml文件加載,並從注銷位置恢復。

我知道那里有很多教程,但是我似乎無法做任何工作。 我需要隨機訪問,並且要在硬盤上實時更新文件。 當前的代碼(遠沒有奏效)顯示了im之后的格式,但是我不了解xml的大多數概念,例如什么是屬性/節點/元素? 教程似乎想假設您知道..

XMLFile = XDocument.Load(@"C:/users.xml");
var users = XMLFile.Descendants( "Users" );
int count = 0;
foreach ( var user in users )
{
  count++;
  userName[count] = user.ToString();

  XElement element = (XMLFile.FirstNode as XElement);
  userPass[count] = element.Value;

  XAttribute attribute = (XMLFile.NextNode as XAttribute);
  userLocation[count] = attribute.Value;

  attribute = (XAttribute)XMLFile.NextNode;
  userRotation[count] = attribute.Value;
}

這個想法是文件將被格式化為這樣的格式(如xml ..)。

Users
    Aaron
        password
        vector3 of location
        Quaternion of Rotation
    SomeoneElse
        hispassword
        Vector3 of location
        Quaternion of rotation
    //and so on....

客戶端登錄后將讀取值,並在整個網絡上發送該值,其他所有方法都起作用,我只是無法獲得任何讀取/寫入xml的方法來工作,因此感謝您的幫助。

首先,它不是有效的XML格式。 我想你的意思是:

<Users>
   <User>
    <Username>...</Username>
    <Password>...</Password>
    <Location>...</Location>
    <Rotation>..</Rotation>
  </User>

</Users>

第二,正如我看到的那樣,將每個用戶值存儲到單獨的數組中,為什么呢? 只需添加一個User類,並定義一個Users集合,供閱讀,請使用以下代碼:

XDocument xDoc = XDocument.Load(@"C:/users.xml");
List<User> users = (from u in xDoc.Descendants("User")
                    select new User {
                        Name = u.Element("Username").Value,
                        Password = u.Element("Password").Value,
                        Location = u.Element("Locations").Value,
                        Rotation = u.Element("Rotation").Value
                    }).ToList();

然后您問“ what is an attribute/node/element

假設我們有這個元素:

<User ID = "23">
   <Username>User123</Username>
</User>

在此特定元素中:

  • IDXml屬性
  • UserUsernameXml元素
  • User是的父元素 Username
  • 一切都是Xml Node ,例如: UserElement Node"User123"Text Node等...

更新:寫入XML

如果您具有此xml結構,則可以簡單地附加這樣的新值(或創建一個新的xml):

我假設您有一個名為users的集合

XElement xmlElement = new XElement("Users",
            from user in users
            select new XElement("User",
                new XElement("Username", user.Username),
                new XElement("Password", user.Password),
                new XElement("Location", user.Location),
                new XElement("Rotation", user.Rotation)));
xmlElement.Save("Users.xml");

更新:驗證用戶

string userName = textBox1.Text;
string password = textBox2.Text;
XDocument xDoc = XDocument.Load(@"C:/users.xml");
var userControl = (from u in xDoc.Descendants("User") 
                    where u.Element("Username").Value == userName
                         && u.Element("Password").Value == password
                           select u).Any();

if(userControl)
{
    // validated...
} else {
 // User doesn't exist or password wrong
}

首先,您可以考慮以下兩種xml文檔格式:

這是使用屬性來存儲數據的方法:

<Users>
  <User UserName="User1" Pass="Pass1" Location="Location1" Rotation="Rotaition1" />
  <User UserName="User2" Pass="Pass2" Location="Location2" Rotation="Rotaition2" />
</Users>

而這是使用元素來存儲您的數據:

<Users>
  <User>
    <UserName>User1</UserName>
    <Pass>Pass1</Pass>
    <Location>Location1</Location>
    <Rotation>Rotation1</Rotation>
  </User>
  <User>
    <UserName>User2</UserName>
    <Pass>Pass2</Pass>
    <Location>Location2</Location>
    <Rotation>Rotation2</Rotation>
  </User>
</Users>

用於創建第一個結構的示例代碼:

    XDocument xDocument = new XDocument();
    XElement rootElement = new XElement("Users");
    rootElement.Add(new XElement("User", new XAttribute("UserName", "User1"), new XAttribute("Pass", "Pass1"), new XAttribute("Location", "Location1"), new XAttribute("Rotation", "Rotaition1")));
    rootElement.Add(new XElement("User", new XAttribute("UserName", "User2"), new XAttribute("Pass", "Pass2"), new XAttribute("Location", "Location2"), new XAttribute("Rotation", "Rotaition2")));
    xDocument.Add(rootElement);

讀取第一個結構的示例代碼:

var xElement = xDocument.Descendants("User").Single(element => element.Attribute("UserName").Value == "User1");

用於創建第二個結構的示例代碼:

    XDocument xDocument = new XDocument();
    XElement rootElement = new XElement("Users");

    XElement userElement = new XElement("User");
    userElement.Add(new XElement("UserName", "User1"));
    userElement.Add(new XElement("Pass", "Pass1"));
    userElement.Add(new XElement("Location", "Location1"));
    userElement.Add(new XElement("Rotation", "Rotation1"));
    rootElement.Add(userElement);

    userElement = new XElement("User");
    userElement.Add(new XElement("UserName", "User2"));
    userElement.Add(new XElement("Pass", "Pass2"));
    userElement.Add(new XElement("Location", "Location2"));
    userElement.Add(new XElement("Rotation", "Rotation2"));
    rootElement.Add(userElement);

    xDocument.Add(rootElement);

最后,示例代碼用於讀取第二種結構:

var xElement = xDocument.Descendants("User").Single(element => element.Element("UserName").Value == "User1");

您可以使用以下示例cas保存並加載xml文檔:

xDocument.Save("Your xml file path"); // using Save() instance method
XDocument xDocument = XDocument.Load("Your xml file path"); // using Load() static method

您可以根據自己的要求,是否易於使用以及最佳實踐來選擇格式良好的xml文檔,是選擇第一種結構還是第二種結構。 在這種情況下,我更喜歡第一種結構。 有關結構良好的xml文檔的更多信息,請參見以下代碼項目文章:結構良好的XML

請注意,以上代碼只是用於創建這兩種xml文檔的一些示例。 在您的情況下,您只需要遍歷users集合並根據每個user對象在循環中創建xml元素。

您還詢問了xml基本概念。 @ Selman22先前的回答是快速正確的,但是有關更多信息,請參見以下參考:

  1. http://www.w3schools.com/xml/default.asp
  2. http://msdn.microsoft.com/en-us/library/bb387019.aspx

只需使用XML序列化器將用戶數組(或用戶對象並使用多個文件)序列化為XML。 http://msdn.microsoft.com/zh-CN/library/182eeyhh(v=vs.110).aspx

寫入文件(來自MSDN)

MySerializableClass myObject = new MySerializableClass();
// Insert code to set properties and fields of the object.
XmlSerializer mySerializer = new 
XmlSerializer(typeof(MySerializableClass));
// To write to a file, create a StreamWriter object.
using (StreamWriter myWriter = new StreamWriter("myFileName.xml"))
{   
   mySerializer.Serialize(myWriter, myObject);
}

從對象讀取(從MSDN)

MySerializableClass myObject;
// Construct an instance of the XmlSerializer with the type
// of object that is being deserialized.
XmlSerializer mySerializer = 
new XmlSerializer(typeof(MySerializableClass));
// To read the file, create a FileStream.
using (FileStream myFileStream = new FileStream("myFileName.xml", FileMode.Open))
{
   // Call the Deserialize method and cast to the object type.
   myObject = (MySerializableClass) 
   mySerializer.Deserialize(myFileStream)
}

順便說一句,“實時”寫入磁盤非常昂貴,您可能需要考慮限制磁盤訪問。 如果您的用戶具有“保存”選項,則可以進行光盤刻錄,也可以使用某種計時器進行刻錄。

就隨機訪問而言,這應該在內存中完成(而不是在文件中)。 基本上,您的流程將是:用戶登錄->從文件中將用戶數據讀取到內存中->用戶操作->更新內存中的對象->用戶保存或“自動保存”->將對象寫入磁盤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM