<?xml version="1.0" encoding="UTF-8"?>
<message xmlns="jabber:client" to="dev_345@localhost/unityXMPP" type="chat" xml:lang="en" from="dev_272@localhost/unityXMPP">
<archived xmlns="urn:xmpp:mam:tmp" id="1503375414608430" by="dev_345@localhost" />
<stanza-id xmlns="urn:xmpp:sid:0" id="1503375414608430" by="dev_345@localhost" />
<body>hi</body>
</message>
我想解析内部XML以获取id属性。 我创建了名称空间,无论我找到了什么。我可以从属性中获得。下面是c#中的代码。
string value = "<message xmlns=\"jabber:client\" to=\"dev_345@localhost/unityXMPP\" type=\"chat\" xml:lang=\"en\" from=\"dev_272@localhost/unityXMPP\"><archived xmlns=\"urn:xmpp:mam:tmp\" id=\"1503375414608430\" by=\"dev_345@localhost\" /><stanza-id xmlns=\"urn:xmpp:sid:0\" id=\"1503375414608430\" by=\"dev_345@localhost\" /><body>hi</body></message>";
XmlDocument xmlDoc = new XmlDocument ();
XmlNamespaceManager namespaces = new XmlNamespaceManager (xmlDoc.NameTable);
namespaces.AddNamespace ("ns", "jabber:client");
namespaces.AddNamespace ("ns1", "urn:xmpp:mam:tmp");
xmlDoc.LoadXml (value);
XmlNode messageNode = xmlDoc.SelectSingleNode ("/ns:message", namespaces);
string sender = messageNode.Attributes ["from"].Value;
string receiver = messageNode.Attributes ["to"].Value;
string message = messageNode.InnerText;
XmlNode timeStampNode = xmlDoc.SelectSingleNode ("/ns:message/ns1:archived");
string timestamp = timeStampNode.Attributes ["id"].Value;
答案 0 :(得分:0)
答案 1 :(得分:0)
这有帮助吗?我使用LINQ To Xml
string xmltext = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><message xmlns=\"jabber:client\" to=\"dev_345@localhost/unityXMPP\" type=\"chat\" xml:lang=\"en\" from=\"dev_272@localhost/unityXMPP\"> <archived xmlns=\"urn:xmpp:mam:tmp\" id=\"1503375414608430\" by=\"dev_345@localhost\" /> <stanza-id xmlns=\"urn:xmpp:sid:0\" id=\"1503375414608430\" by=\"dev_345@localhost\" /> <body>hi</body></message>";
var xdoc = XDocument.Parse(xmltext);
foreach (var item in xdoc.Root.Descendants())
{
if (item.Name.LocalName == "archived")
Console.WriteLine(item.Attribute("id").Value);
}
答案 2 :(得分:0)
尝试按照xml linq获取所有数据
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 = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var message = doc.Descendants().Where(x => x.Name.LocalName == "message").Select(x => new {
to = (string)x.Attribute("to"),
type = (string)x.Attribute("type"),
lang = (string)x.Attributes().Where(y => y.Name.LocalName == "lang").FirstOrDefault(),
from = (string)x.Attribute("from"),
messages = x.Elements().Select(y => new {
name = y.Name.LocalName,
id = (string)y.Attribute("id"),
by = (string)y.Attribute("by"),
value = (string)y
}).ToList()
}).FirstOrDefault();
}
}
}