Arun Pandey Arun Pandey - 1 month ago 9
C# Question

Parse XMPP inner xml

<?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>


I wanted to parse the inner XML to fetch the id attribute.
I have created namespace whatsoever I have found. I am able to get to, from attributes. Below is the code in 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;

Answer Source

Does this help? I used 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);                
}