I,ve searched a bit, but didn't find anythings that I think is right for an answer, I'm using a XDocument to load my xml, but I'm having some trouble to transform it into an array
<?xml version="1.0" encoding="UTF-8"?>
<document>
<sNone>
<October>3.21</October>
<November>-5.41</November>
<December>-15.81</December>
<January>-21.69</January>
<February>-21.70</February>
<March>-12.60</March>
<April>-6.41</April>
<May>-0.06</May>
<June>5.42</June>
<July>13.32</July>
<August>14.12</August>
<September>7.55</September>
</sNone>
<sLichen>
<October>1.99</October>
...
</sLichen>
</document>
I'm loading my XML like so
XDocument doc = XDocument.Parse();
but I'm confused on how to return a 1D array because I have multiple descendant.
EDIT
What I'm aiming to get is an array like this
{3.21, -5.41, -15.81, -21.69, -21.70, -12.60, -6.41, -0.06, 5.42, 13.32, 14.12, 7.55}
This should do the trick :
var doc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?....";
XDocument xdoc = XDocument.Parse(doc);
var items = xdoc.Root.Elements("sNone").Descendants().Select(d => d.Value).ToArray();
Console.WriteLine(items);
Or if you want decimals :
var items2 = xdoc.Root.Elements("sNone").Descendants().Select(d => decimal.Parse(d.Value)).ToArray();
Hope this helps.
Related
Please read the code bellow. There I am trying to grab all elements under the <GetSellerListResponse> node, then my goal is to grab TotalNumberOfPages value (currently it's 9 as you can see in the XML).
But my problem is I am getting an error:
System.InvalidOperationException: 'Sequence contains no elements'
Error screenshot is attached for better understanding. Can you tell me what's wrong the way I am trying to grab all elements? Also if possible can you tell how I can grab that 9 from TotalNumberOfPage?
Thanks in advance
C#:
var parsedXML = XElement.Parse(xml);
var AllElements = parsedXML.Descendants("GetSellerListResponse")
.Where(x => x.Attribute("xmlns").Value.Equals("urn:ebay:apis:eBLBaseComponents"))
.First();
XML:
<?xml version="1.0" encoding="UTF-8"?>
<GetSellerListResponse xmlns="urn:ebay:apis:eBLBaseComponents">
<Timestamp>2018-06-20T17:26:29.518Z</Timestamp>
<Ack>Success</Ack>
<Version>1059</Version>
<Build>E1059_CORE_APISELLING_18694654_R1</Build>
<PaginationResult>
<TotalNumberOfPages>9</TotalNumberOfPages>
</PaginationResult>
</GetSellerListResponse>
EDIT: your mistake is the usage of XElement: it is searching for matching elements in the children of <GetSellerListResponse>; that's why you are not getting any result. Change XElement.Parse(xml); to XDocument.Parse(xml);, then the following snippets will work.
You could simply check for the local name:
var AllElements = parsedXML.Descendants().First(x => x.Name.LocalName == "GetSellerListResponse");
I would suggest to use XDocument instead of XElement for parsedXML, because you could shorten the above query to var AllElements = parsedXML.Root;
Another thing you could try is prepending the namespace:
XNamespace ns = "urn:ebay:apis:eBLBaseComponents";
var AllElements = parsedXML.Descendants(ns + "GetSellerListResponse").First();
To answer the question "how to get the number of pages":
var pages = AllElements.Element(ns + "PaginationResult").Element(ns + "TotalNumberOfPages").Value;
I would suggest using the XmlDocument class from System.Xml.
Try the code below:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<GetSellerListResponse xmlns=\"urn:ebay:apis:eBLBaseComponents\"><Timestamp>2018-06-20T17: 26:29.518Z</Timestamp><Ack>Success</Ack><Version>1059</Version><Build>E1059_CORE_APISELLING_18694654_R1</Build><PaginationResult><TotalNumberOfPages>9</TotalNumberOfPages></PaginationResult></GetSellerListResponse>");
XmlNodeList nodeList = doc.GetElementsByTagName("TotalNumberOfPages");
In this case, your nodeList will have just the one element for TotalNumberOfPages and you can access the value by checking
nodeList.FirstOrDefault().InnerText
I'm in a situation where i need to get rid of my parentnode, but not my childnodes.
Here is how it loooks:
<?xml version="1.0" encoding="utf-8"?>
<ns0:MisMessage>
<mislife>
<party/>
<datetime>2018-06-04T09:35:33</datetime>
<insurance">
<number>123</number>
<amount>3</amount>
<indicator></indicator>
<text>asd</text>
</insurance>
</mislife>
<ns0:Message/>
</ns0:MisMessage>
And here is how i want it to look after i'm done.
<mislife>
<party/>
<datetime>2018-06-04T09:35:33</datetime>
<insurance">
<number>123</number>
<amount>3</amount>
<indicator></indicator>
<text>asd</text>
</insurance>
</mislife>
Is there any easy way to do this? I have tried and tried and tried. I have been looking all over the internet and i can't find out how to do it. The thing i want to remove will always be named ns0: in the beggning. Can i do it by removeing with substrings? THANKS!
I solved it like below, i converted the XMLDocument to XDocument and then used the descendants. Just like #bommelding showed in his example. Thank you all!
var xDocument = ToXDocument(xmlDocument);
if (xDocument != null)
{
var mislife = xDocument.Descendants("mislife").FirstOrDefault();
if (mislife != null)
{
return mislife;
}
}
public static XDocument ToXDocument(XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
XDocument doc = XDocument.Load(fileName);
XElement data = doc
.Descendants("mislife") // find your target
.Single(); // be brave, there should be exactly 1
data.Save(otherFileName); // saves with document <? ... ?>
Simple way with Linq (remember to add using System.Xml.Linq;):
string testxml = #"
<?xml version=""1.0"" encoding=""UTF-8""?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";
XDocument doc = XDocument.Parse(testxml).Descendants().First().Document;
doc will be your xml without the root element
XDocument can load from files with
XDocument.Load("path");
or read XML like I did with
Xml.Parse("<xml....>");
and have also other options.
Result is:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Let's say I have an xml string:
<?xml version="1.0" encoding="UTF-8"?>
<Return version="1.0">
<File>1</File>
<URL>2</URL>
<SourceUUID>1191CF90-5A32-4D29-9F90-24B2EXXXXXX0</SourceUUID>
</Return>
and I want to extract the value of SourceUUID, how?
I tried:
XDocument doc = XDocument.Parse(xmlString);
foreach (XElement element in doc.Descendants("SourceUUID"))
{
Console.WriteLine(element);
}
If all you want is the content of the SourceUUID element, and there's only going to be 1 in the XML, you can do this:
XDocument doc = XDocument.Parse(xmlString);
var value = doc.Descendants("SourceUUID").SingleOrDefault()?.Value;
If there are going to be more than one, you can do this:
var values = doc.Descendants("SourceUUID").Select(x => x.Value);
This gives you an enumerable of strings that are the text values of the elements.
I am trying to create a list of user id's from an xml document in C#. Here is my latest try:
string xml = WebexAutomation.LstSummaryUser();
XDocument doc = XDocument.Parse(xml)
var result = doc.Descendants("webExId").Single().Value;
Console.WriteLine(result);
My XML looks like it has multiple users and I am trying to create list of each webExId
<?xml version="1.0" encoding="ISO-8859-1"?>
<serv:message xmlns:serv="http://www.webex.com/schemas/2002/06/service" xmlns:com="http://www.webex.com/schemas/2002/06/common" xmlns:use="http://www.webex.com/schemas/2002/06/service/user">
<serv:header>
<serv:response>
<serv:result>SUCCESS</serv:result>
<serv:gsbStatus>PRIMARY</serv:gsbStatus>
</serv:response>
</serv:header>
<serv:body>
<serv:bodyContent xsi:type="use:lstsummaryUserResponse" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<use:user>
<use:webExId>kkkk</use:webExId>
<use:firstName>kkkk</use:firstName>
<use:lastName>llllll</use:lastName>
<use:email>kkkkkk</use:email>
<use:registrationDate>06/07/2014 01:17:13</use:registrationDate>
<use:active>DEACTIVATED</use:active>
<use:timeZoneID>11</use:timeZoneID>
</use:user>
<use:user>
<use:webExId>jjjj</use:webExId>
<use:firstName>ssss</use:firstName>
<use:lastName>dddd</use:lastName>
<use:email>dfdfdf</use:email>
<use:registrationDate>06/10/2013 12:23:52</use:registrationDate>
<use:active>DEACTIVATED</use:active>
<use:timeZoneID>11</use:timeZoneID>
</use:user>
<use:matchingRecords>
<serv:total>44</serv:total>
<serv:returned>10</serv:returned>
<serv:startFrom>1</serv:startFrom>
</use:matchingRecords>
</serv:bodyContent>
</serv:body>
</serv:message>
Any suggestions?
Try this instead
var webExId = XName.Get("webExId", "http://www.tempuri.org");
var webExIds = doc.Descendants(webExId);
I am trying to read a very basic SVG file which has the following contents:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="600" height="300" version="1.1" xmlns="http://www.w3.org/2000/svg">
<g stroke="black" >
<line x1="75" y1="160" x2="525" y2="160" stroke-width="10"/>
</g>
</svg>
I am trying to get a collection of line elements. However, the following code does not work:
XDocument XD = XDocument.Load(PathToFile);
XElement SVG_Element = XD.Root;
var adam = SVG_Element.Elements("line");
Upon inspecting the variables, the document is loaded properly, but the variable "adam" remains null, as if it does not find any elements with that name. Any help is appreciated.
Edit: Using Descendants does not fix this. It still comes up empty.
Alright guys, I did figure this out. Apparently I need to specify the namespace as part of the QName:
var adam = SVG_Element.Descendants("{http://www.w3.org/2000/svg}line");
The line element is a grandchild of the root, not a child. Try the Descendants() method of the XDocument instead.
Try something like this:
Dim xmldoc As XDocument = XDocument.Load(Server.MapPath("PathtosvgFile"))
Dim Info As IEnumerable(Of XElement) = _
From typeElement In xmldoc.Descendants.Descendants
Where typeElement.Parent = "g"
Select typeElement
Dim tel As XElement
For Each tel In Info.DescendantsAndSelf.Distinct()
'Access each descendant here and do something.
Next
I never used XDocument to parse Xml files. I use XmlDocument. But I believe both work on a similar fashion.
My guess is that you should first query for the "g" element, and then for the "line" element, something like the following:
XDocument XD = XDocument.Load(PathToFile);
XElement SVG_Element = XD.Root;
var gs = SVG_Element.Elements("g");
var adam = gs[0].Elements("line");
Hope it helps.
XDocument SVGDoc = XDocument.Load(yourfile);
XElement svg_Element = SVGDoc.Root;
IEnumerable<XElement> gElement = from e1 in svg_Element.Elements("{http://www.w3.org/2000/svg}g")
select e1;
int nCounter = 0;
foreach (XElement myElement in gElement)
{
...
}