Hello guys Im trying to get access to specified values in XML. But my POST request return it as string in this format:
string smsList = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<response>\n\t<Count>2</Count>\n\t<Messages>\n\t\t<Message>\n\t\t\t<Smstat>0</Smstat>\n\t\t\t<Index>20001</Index>\n\t\t\t<Phone> number</Phone>\n\t\t\t<Content>Test4</Content>\n\t\t\t<Date>2021-12-11 14:24:23</Date>\n\t\t\t<Sca> number</Sca>\n\t\t\t<SaveType>4</SaveType>\n\t\t\t<Priority>0</Priority>\n\t\t\t<SmsType>1</SmsType>\n\t\t</Message>\n\t\t<Message>\n\t\t\t<Smstat>0</Smstat>\n\t\t\t<Index>20000</Index>\n\t\t\t<Phone> number</Phone>\n\t\t\t<Content>Test3</Content>\n\t\t\t<Date>2021-12-11 14:02:48</Date>\n\t\t\t<Sca> number</Sca>\n\t\t\t<SaveType>4</SaveType>\n\t\t\t<Priority>0</Priority>\n\t\t\t<SmsType>1</SmsType>\n\t\t</Message>\n\t</Messages>\n</response>"
smsList = smsList.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
smsList = smsList.Replace("\n", "");
smsList = smsList.Replace("\t", "");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(smsList);
But issue is I tested mulplite variation to get access to attribute messages/message but it return nothing.
CodePudding user response:
Try this:
using System.Xml;
using System.Xml.Linq;
using System.Linq;
and
var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<response>\n\t<Count>2</Count>\n\t<Messages>\n\t\t<Message>\n\t\t\t<Smstat>0</Smstat>\n\t\t\t<Index>20001</Index>\n\t\t\t<Phone> number</Phone>\n\t\t\t<Content>Test4</Content>\n\t\t\t<Date>2021-12-11 14:24:23</Date>\n\t\t\t<Sca> number</Sca>\n\t\t\t<SaveType>4</SaveType>\n\t\t\t<Priority>0</Priority>\n\t\t\t<SmsType>1</SmsType>\n\t\t</Message>\n\t\t<Message>\n\t\t\t<Smstat>0</Smstat>\n\t\t\t<Index>20000</Index>\n\t\t\t<Phone> number</Phone>\n\t\t\t<Content>Test3</Content>\n\t\t\t<Date>2021-12-11 14:02:48</Date>\n\t\t\t<Sca> number</Sca>\n\t\t\t<SaveType>4</SaveType>\n\t\t\t<Priority>0</Priority>\n\t\t\t<SmsType>1</SmsType>\n\t\t</Message>\n\t</Messages>\n</response>";
var document = XDocument.Parse(xmlStr);
var messages = document.Root.Descendants("Message").Select(x => new string[]
{
x.Descendants("Smstat").FirstOrDefault().Value,
x.Descendants("Index").FirstOrDefault().Value,
x.Descendants("Phone").FirstOrDefault().Value.ToString(),
x.Descendants("Content").FirstOrDefault().Value,
x.Descendants("Date").FirstOrDefault().Value,
x.Descendants("Sca").FirstOrDefault().Value,
x.Descendants("SaveType").FirstOrDefault().Value,
x.Descendants("Priority").FirstOrDefault().Value,
x.Descendants("SmsType").FirstOrDefault().Value
}).ToList();
Console.WriteLine("Smstat;Index;Phone;Content;Date;Sca;SaveType;Priority;SmsType");
foreach (var msg in messages)
{
Console.WriteLine(String.Join(";", msg));
}
(It's also on a fiddle if you want to try it)