从简单的XML文档中获取价值

时间:2018-04-05 02:24:53

标签: c# xml unity3d

我有以下XML

<User 
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://schemas.datacontract.org/2004/07/GaryLeaderboardsAPI.Models">
    <Game_ID>3</Game_ID>
    <UserGUID>e00d3560-4133-4ba6-8bba-e6c8659468b4</UserGUID>
    <UserName>tony2</UserName>
    <User_ID>16</User_ID>
</User>

使用C#我将其加载到XMLDocument中,如何检索UserGUID值?

3 个答案:

答案 0 :(得分:3)

利用System.Xml.Linq,你可以做到

string xml = "..."; // your inline XML
var doc = System.Xml.Linq.XDocument.Parse(xml);

string xmlFile = "..."; // your XML filename
var doc = System.Xml.Linq.XDocument.Load(xmlFile);

然后,获取UserGUID

var userGuid = doc.Descendants().Where(x=>x.Name.LocalName == "UserGUID").First().Value;

答案 1 :(得分:2)

这对你有用。

string xml = "<User xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/GaryLeaderboardsAPI.Models\">" +
        "<Game_ID>3</Game_ID>" +
        "<UserGUID>e00d3560-4133-4ba6-8bba-e6c8659468b4</UserGUID>" +
        "<UserName>tony2</UserName>" +
        "<User_ID>16</User_ID>" +
        "</User>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

var id = doc.GetElementsByTagName("UserGUID")[0].InnerText;

答案 2 :(得分:2)

您需要使用命名空间。我经常使用mipnw方法(可能从我的一个帖子中窃取了想法)。请参阅以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement user = doc.Root;
            XNamespace ns = user.GetDefaultNamespace();

            string UserGUID = (string)user.Element(ns + "UserGUID");
        }
    }
}