I have a problem with the following XML:
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ReportName="SearchQueryPerformanceReport_05_24_2022_11_19_51" ReportTime="3/24/2022,5/23/2022" TimeZone="Various" ReportAggregation="Daily" LastCompletedAvailableDay="5/24/2022 10:20:00 AM (GMT)" LastCompletedAvailableHour="5/24/2022 10:20:00 AM (GMT)" PotentialIncompleteData="true" xmlns="http://adcenter.microsoft.com/advertiser/reporting/v5/XMLSchema">
<Table>
<Row>
<AccountName value="fffffff" />
<CampaignName value="dddddddddddddd" />
<CampaignId value="424769594" />
<Clicks value="1" />
<CostPerConversion value="" />
<Ctr value="100.00%" />
<AccountId value="1848" />
<DeviceType value="Computer" />
<AverageCpc value="0.25" />
<AveragePosition value="0.00" />
<BidMatchType value="Exact" />
<AdGroupName value="eeeeeeeeee" />
<AdGroupId value="135899347066" />
<AdId value="84933705" />
<ConversionRate value="0.00%" />
<Keyword value="zusammen at" />
<KeywordId value="84937818" />
<Language value="German" />
<Conversions value="0" />
<Impressions value="1" />
<Spend value="0.25" />
<TimePeriod value="2022-04-13" />
<SearchQuery value="zusammen.at" />
</Row>
</Table>
<Copyright>©2022 Microsoft Corporation. All rights reserved. </Copyright>
</Report>
When I use this code the XML does not return any element.
XDocument doc = XDocument.Parse(LstSearchTermV.XmlContent); var result2 = from s in doc.Descendants("Table");
or
var result2 = from s in doc.Element("Table");
or
var result2 = from s in doc.Elements("Row");
I have tried different ways but nothing.
I test with other XML and have same problem.
Does anyone know why, where is the problem?
Update: I try it: XDocument Elements return null
It work and I get elements but, when I try to get values is very long code, example:
var ValueElement = el.Element(XName.Get("CampaignId", doc.Root.GetDefaultNamespace().NamespaceName)).Attributes().Where(w => w.Name == "value");
¿Is any code more short or more optimized to get data of XDocument?
CodePudding user response:
Yes, you can definitely write simpler code than that, using the XNamespace
type and the various operators and conversions available to create an XName
, and using the Attribute
method that looks for an attribute with a given name:
// Or XNamespace ns = doc.Root.GetDefaultNamespace()
XNamespace ns = "http://adcenter.microsoft.com/advertiser/reporting/v5/XMLSchema";
var value = el.Element(ns "CampaignId").Attribute("value");
value
will be null if there's no such attribute.