Set Order Precedence Between XMLArray and XMLElement - c#

I am trying to serialize an XML with C#, which has XMLElement and XMLArray.
When Serialized am getting XML as
<TestPlanResult xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" TestPlanRunStartedDateTime="02/10/2016 2:53 AM" TestPlanName="DataReconciliation" TestPlanRunTime="00:00:44.8979705"TestCaseCount="2" PassingTestCaseCount="2" FailingTestCaseCount="0" RemediationTestCount="0" Pass="true" ValidationPointCount="3">
<TestCaseResults Pass="true" Parameters="" RemediationToFollow="false" TestCaseName="0.1.5.2 InstallationMaintenance.GetInstallationFiles" RunTime="00:00:20.7972729" ValidationPointCount="2">
</TestCaseResults>
<TestCaseResults Pass="true" Parameters="" RemediationToFollow="false" TestCaseName="CheckForFullCompletion" RunTime="" ValidationPointCount="1">
</TestCaseResults>
<ProductVersions DbVersion="" AIEVersion="8001" ConsoleVersion="8001" MediatorVersion="9000" MonitorVersion="8001" DataIndexerVersion="1504" JobManagerVersion="" ARMVersion="8001"/>
</TestPlanResult>
In Result, I want to see ProductVersion Node before TestCaseResults Node,
So, XML looks like
<TestPlanResult xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" TestPlanRunStartedDateTime="02/10/2016 2:53 AM" TestPlanName="DataReconciliation" TestPlanRunTime="00:00:44.8979705"TestCaseCount="2" PassingTestCaseCount="2" FailingTestCaseCount="0" RemediationTestCount="0" Pass="true" ValidationPointCount="3">
<ProductVersions DbVersion="" AIEVersion="8001" ConsoleVersion="8001" MediatorVersion="9000" MonitorVersion="8001" DataIndexerVersion="1504" JobManagerVersion="" ARMVersion="8001"/>
<TestCaseResults Pass="true" Parameters="" RemediationToFollow="false" TestCaseName="0.1.5.2 InstallationMaintenance.GetInstallationFiles" RunTime="00:00:20.7972729" ValidationPointCount="2">
</TestCaseResults>
<TestCaseResults Pass="true" Parameters="" RemediationToFollow="false" TestCaseName="CheckForFullCompletion" RunTime="" ValidationPointCount="1">
</TestCaseResults>
</TestPlanResult>
I have already tried putting ProductVersions before TestCaseResults in C# property declrations and XML Element Order, but it is not working .
Thanks in Advance

Related

XDocument.XPathSelectElements doesn't work as expected

Sometimes C# driving me crazy, guys :) !
I tried a very simple code:
String pathToXMLFile = openFileDialog2.FileName;
var xdoc = XDocument.Load(pathToXMLFile);
var xElements = xdoc.XPathSelectElements("//NotificationData");
foreach (XElement xe in xElements)
{
Console.WriteLine(xe);
xe.RemoveAll();
}
xdoc.Save("c:/Temp/ReestrZalogovRuManyCollateralItemsSimple_output.xml");
and a very simple XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PledgeNotificationToNotary xmlns="http://fciit.ru/eis2/ruzdi/types/2.2" version="2.2">
<NotificationId>7d8b62c2-7682-43f8-8a2c-ef4296296210</NotificationId>
<NotificationNotaryAddress/>
<NotificationData version="2.2">
<FormUZ1>
<PersonalProperties>
<PersonalProperty>
<OtherProperty>
<Description>Движимое имущество, согласно перечню по договору купли-продажи </Description>
</OtherProperty>
</PersonalProperty>
</PersonalProperties>
<Pledgors>
<Pledgor>
<Organization>
<RussianOrganization>
<NameFull>dgdgdfgdf</NameFull>
<OGRN>35345345</OGRN>
<INN>34534545</INN>
<Address>
<RegionCode>77</RegionCode>
<Region>Москва</Region>
<Street>Малая Семеновская</Street>
<House>fggdgdf</House>
<Building>dfgdfg</Building>
<Apartment>54654646dfg</Apartment>
</Address>
</RussianOrganization>
</Organization>
</Pledgor>
</Pledgors>
<Pledgee>
<Pledgee>
<Organization>
<RussianOrganization>
<NameFull>Тимер Банк (публичное акционерное общество)</NameFull>
<OGRN>1021600000146</OGRN>
<INN>1653016689</INN>
<Address>
<RegionCode>16</RegionCode>
<Region>Республика Татарстан (Татарстан)</Region>
<City>Казань</City>
<Street>проспект Ибрагимова</Street>
<House>58</House>
</Address>
<Email>dfgdgdgdg#timerbank.ru</Email>
</RussianOrganization>
</Organization>
</Pledgee>
</Pledgee>
<PledgeContract>
<Name>ДОГОВОР О ЗАЛОГЕ</Name>
<Date>2018-08-20</Date>
<Number>№ДОКЛЮ/7777/77-7</Number>
<TermOfContract>«01» июня 2028 года</TermOfContract>
</PledgeContract>
<NotificationApplicant>
<Role>2</Role>
<Organization>
<NameFull>Тимер Банк (публичное акционерное общество)</NameFull>
<URN>1021600000146</URN>
<UINN>1653016689</UINN>
<Email>fgdfggsdfgsdfg#timerbank.ru</Email>
</Organization>
<Attorney>
<Name>
<Last>dfgfg</Last>
<First>dfgsdfg</First>
<Middle>sdfgdfg</Middle>
</Name>
<BirthDate>1967-08-01</BirthDate>
<Authority>приказ dgdfgdfgfdg</Authority>
<PersonDocument>
<Code>33</Code>
<Name>Паспорт гражданина Российской Федерации</Name>
<SeriesNumber>2323 232323</SeriesNumber>
</PersonDocument>
<PersonAddress>
<AddressRF registration="true">
<RegionCode>16</RegionCode>
<Region>Республика Татарстан (Татарстан)</Region>
<City>Казань</City>
<Street>gfdgdfg</Street>
<House>343434</House>
</AddressRF>
</PersonAddress>
</Attorney>
</NotificationApplicant>
</FormUZ1>
</NotificationData>
</PledgeNotificationToNotary>
The problem is xdoc.XPathSelectElements in this code doesn't return any Elements.
I thought, may be I haven't yet woken up and tried to test my XML and XPath in the first site in Google for XPath online evulation - https://www.freeformatter.com/xpath-tester.html and my XPath //NotificationData works with this XML like a charm.
But why it doesn't work in C#? :)
Thank you in advance!

SelectNodes does not return the child values

I am new to XPath. I read the entire W3Schools tutorial. I would like to get all the <schedule> nodes of my document. I can get all the child elements of my document with child::* but as soon as I add <schedule> like the following, I get zero results:
XmlDocument dom = new XmlDocument();
dom.Load(textBoxFilePath.Text);
XmlNodeList jobElements = dom.DocumentElement.SelectNodes("child::schedule");
This is my xml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- This file contains job definitions in schema version 2.0 format -->
<job-scheduling-data version="2.0" xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<processing-directives>
<overwrite-existing-data>true</overwrite-existing-data>
</processing-directives>
<schedule>
<job>
<name>receiverjob</name>
<group>receivergroup</group>
<job-type>Quartz.Server.ArgumentReceiverJob, Quartz.Server</job-type>
<job-data-map>
<entry>
<key>receivedargument</key>
<value>hamburger</value>
</entry>
</job-data-map>
</job>
<trigger>
<simple>
<name>argumentreceiverJobTrigger</name>
<group>argumentreceiverGroup</group>
<description>Simple trigger to simply fire sample job</description>
<job-name>receiverjob</job-name>
<job-group>receivergroup</job-group>
<misfire-instruction>SmartPolicy</misfire-instruction>
<repeat-count>-1</repeat-count>
<repeat-interval>10000</repeat-interval>
</simple>
</trigger>
<job>
<name>batchjob</name>
<group>batchGroup</group>
<job-type>Quartz.Server.BatchJob, Quartz.Server</job-type>
<durable>true</durable>
<recover>false</recover>
</job>
<trigger>
<cron>
<name>Trigger2</name>
<group>DEFAULT</group>
<job-name>batchjob</job-name>
<job-group>batchGroup</job-group>
<cron-expression>0/15 * * * * ?</cron-expression>
</cron>
</trigger>
</schedule>
</job-scheduling-data>
What I would ultimately like to achieve is to get all the <name>s of the <job>s that match a string.
That's because your XML has default namespace :
xmlns="http://quartznet.sourceforge.net/JobSchedulingData"
Register a prefix that points to default namespace, then use that prefix along with the element's local name to reference an element in namespace :
XmlDocument dom = new XmlDocument();
dom.Load(textBoxFilePath.Text);
XmlNamespaceManager nsManager = new XmlNamespaceManager(dom.NameTable);
nsManager.AddNamespace("d", dom.DocumentElement.NamespaceURI);
XmlNodeList jobElements = dom.DocumentElement.SelectNodes("child::d:schedule", nsManager);
.NET fiddle demo
You could use the following code to find all schedule elements.
XmlDocument dom = new XmlDocument();
dom.Load(textBoxFilePath.Text);
XmlNodeList jobElements = dom.GetElementsByTagName("schedule");

Reading an innertext from an xml document

How do I get the innertext of the OverallResult element using SelectSingleNode?
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ProcessResp xmlns="http://www.w3.org/2005/Atom">
<Result>
<OverallResult>Success</OverallResult>
var doc = new XmlDocument();
doc.LoadXml(xml);
var text = doc.SelectSingleNode("Example/Node/text()").InnerText; // or .Value
returns
"Some text here\r\n "
and text.Trim() returns
"Some text here"
Please go through the below link for XML related queries its very useful for begginers!
http://www.dotnetcurry.com/ShowArticle.aspx?ID=564
for your answer(i havnt tried it though try by changing like this in ur code)
doc.SelectSingleNode("soap/ProcessResp/ Result/OverallResult/text()").InnerText;

XML Canonicalisation in C#

I am trying to create a canonical form of an XML input by using an XPATH expression however I am not sure if I can receiving the correct output form the document.
I am using this expression at the moment but I am expected to be able to use the second one shown however this returns no results.
I add this namespace otherwise the top does not work either
xmlnsManager.AddNamespace("x", "http://www.mytest.uk/tester");
Current XPATH -
x:testApplications/descendant-or-self::node()|//x:testApplications//#*
Expected XPATH -
/testApplicationsBatch/testApplications|/testApplicaitonsBatch/testApplications//*
In XPathVisualizer the expected path gives me the correct output however in .NET it does not.
XML DOCUMENT
<testApplicationsBatch xmlns="http://www.mytest.uk/tester" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.mytest.uk/test testApplications.xsd">
<testMessageHeader>
<MessageID>00000020</MessageID>
<RegisteredBody>20130900006</RegisteredBody>
<Timestamp>2013-06-21T11:34:02</Timestamp>
<MessageCheck>8iOc6vuolwy1pFlfaSJcLZKPSruLlhYuXeTw1hCRAYi9N3MynGveElyECPyZUOBJ</MessageCheck>
</testMessageHeader>
<testApplications>
<testApplication>
<ApplicantDetails>
<Title>DR</Title>
<Forename>REJECT</Forename>
<Middlenames>
<Middlename>INTEGRITY</Middlename>
</Middlenames>
<PresentSurname>VALIDATIONTESTCASETWELVE</PresentSurname>
<CurrentAddress>
<Address>
<AddressLine1>10 LODGE COURT</AddressLine1>
<AddressTown>STAINING</AddressTown>
<AddressCounty>LANCASHIRE</AddressCounty>
<Postcode>FY3 0EJ</Postcode>
<CountryCode>GB</CountryCode>
</Address>
<ResidentFromGyearMonth>2003-07</ResidentFromGyearMonth>
</CurrentAddress>
<DateOfBirth>1977-01-01</DateOfBirth>
<Gender>male</Gender>
<NINumber>NM433816D</NINumber>
<AdditionalApplicantDetails>
<BirthTown>BLACKPOOL</BirthTown>
<BirthCounty>LANCASHIRE</BirthCounty>
<BirthCountry>GB</BirthCountry>
<BirthNationality>BRITISH</BirthNationality>
<ContactNumber>01253 897888</ContactNumber>
<UnspentConvictions>n</UnspentConvictions>
<DeclarationByApplicant>y</DeclarationByApplicant>
<LanguagePreference>english</LanguagePreference>
</AdditionalApplicantDetails>
<ApplicantIdentityDetails>
<IdentityVerified>y</IdentityVerified>
<EvidenceCheckedBy>RICHARD SMITH</EvidenceCheckedBy>
</ApplicantIdentityDetails>
</ApplicantDetails>
<PotentialEmployerDetails>
<PositionAppliedFor>HEAD TEACHER</PositionAppliedFor>
<OrganisationName>HODGSON HIGH SCHOOL</OrganisationName>
</PotentialEmployerDetails>
<RBdetails>
<RBApplicationReference>D00000128</RBApplicationReference>
<RBNumber>20130900006</RBNumber>
<CSigNumber>20130900021</CSigNumber>
<DisclosureType>standard</DisclosureType>
<WorkingWithVulnerableAdults>n</WorkingWithVulnerableAdults>
<WorkingWithChildren>n</WorkingWithChildren>
<CurrentAddressDetailsChecked>y</CurrentAddressDetailsChecked>
<Volunteer>y</Volunteer>
<WorkingAtHomeAddress>n</WorkingAtHomeAddress>
</RBdetails>
</testApplication>
</testApplications>
</testApplicationsBatch>
RETURNED CANONICAL DOCUMENT
<testApplications xmlns="http://www.mytest.uk/tester" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<testApplication>
<ApplicantDetails>
<Title>MRS</Title>
<Forename>A'BCD THISISTEST CASEONEFORENAME</Forename>
<Middlenames>
<Middlename>MIDDLENAMEOFTESTCASEONE</Middlename>
</Middlenames>
<PresentSurname>ABCDEFTHISISTESTCASEONESURNAME</PresentSurname>
<CurrentAddress>
<Address>
<AddressLine1>28 BROCKLEWOOD'S AVENUE</AddressLine1>
<AddressLine2>NEAR/HIGHCROSS-(PUB)</AddressLine2>
<AddressTown>POULTON-LE-FYLDE</AddressTown>
<AddressCounty>LANCASHIRE-TEST-COUNTY</AddressCounty>
<Postcode>FY6 7SJ</Postcode>
<CountryCode>GB</CountryCode>
</Address>
<ResidentFromGyearMonth>2013-07</ResidentFromGyearMonth>
</CurrentAddress>
<PreviousAddress>
<Address>
<AddressLine1>1(FLAT2) CUMBERLAND HOUSE</AddressLine1>
<AddressLine2>A'B-C THISISTESTCASEONEADDRESSLINETWO</AddressLine2>
<AddressTown>ABERYSTH-TOWN</AddressTown>
<AddressCounty>G</AddressCounty>
<Postcode>L2 0QN</Postcode>
<CountryCode>GB</CountryCode>
</Address>
<ResidentDates>
<ResidentFromGyearMonth>1997-01</ResidentFromGyearMonth>
<ResidentToGyearMonth>2013-07</ResidentToGyearMonth>
</ResidentDates>
</PreviousAddress>
<DateOfBirth>1977-01-13</DateOfBirth>
<Gender>female</Gender>
<NINumber>NM433816D</NINumber>
<AdditionalApplicantDetails>
<BirthSurname>A'B-CBIRTHSURNAME</BirthSurname>
<BirthSurnameUntil>2000</BirthSurnameUntil>
<OtherSurnames>
<OtherSurname>
<Name>OTHER SURNAME NAME</Name>
<UsedFrom>2000</UsedFrom>
<UsedTo>2000</UsedTo>
</OtherSurname>
</OtherSurnames>
<OtherForenames>
<OtherForename>
<Name>OTHERFORENAMENAMETESTONE</Name>
<UsedFrom>1977</UsedFrom>
<UsedTo>2000</UsedTo>
</OtherForename>
</OtherForenames>
<BirthTown>ASHTON-UNDER-LYME</BirthTown>
<BirthCounty>/1-'&COUNTYTESTONE</BirthCounty>
<BirthCountry>WS</BirthCountry>
<BirthNationality>GERMAN/-0'FRENCH</BirthNationality>
<ContactNumber>01253 897888/EXT - 1234</ContactNumber>
<UnspentConvictions>y</UnspentConvictions>
<DeclarationByApplicant>y</DeclarationByApplicant>
<LanguagePreference>english</LanguagePreference>
</AdditionalApplicantDetails>
<ApplicantIdentityDetails>
<IdentityVerified>y</IdentityVerified>
<EvidenceCheckedBy>RICHARD SMITH</EvidenceCheckedBy>
<PassportDetails>
<PassportNumber>12345678912</PassportNumber>
<PassportDob>1977-01-13</PassportDob>
<PassportNationality>BRITISH</PassportNationality>
<PassportIssueDate>2001-01-13</PassportIssueDate>
</PassportDetails>
<DriverLicenceDetails>
<DriverLicenceNumber>ABCDE 701017 AB1CS</DriverLicenceNumber>
<DriverLicenceDOB>1977-01-13</DriverLicenceDOB>
<DriverLicenceType>paper</DriverLicenceType>
<DriverLicenceValidFrom>2003-01-02</DriverLicenceValidFrom>
<DriverLicenceIssueCountry>IO</DriverLicenceIssueCountry>
</DriverLicenceDetails>
</ApplicantIdentityDetails>
</ApplicantDetails>
<PotentialEmployerDetails>
<PositionAppliedFor>CARETAKER'S ASSISTANT</PositionAppliedFor>
<OrganisationName>BIDE-A-WEE REST HOME'S/(ELDERLY&INFIRM)</OrganisationName>
</PotentialEmployerDetails>
<RBdetails>
<RBApplicationReference>ARM16</RBApplicationReference>
<RBNumber>20130800000</RBNumber>
<CSigNumber>20130800025</CSigNumber>
<DisclosureType>standard</DisclosureType>
<WorkingWithVulnerableAdults>n</WorkingWithVulnerableAdults>
<WorkingWithChildren>n</WorkingWithChildren>
<CurrentAddressDetailsChecked>y</CurrentAddressDetailsChecked>
<Volunteer>y</Volunteer>
<WorkingAtHomeAddress>n</WorkingAtHomeAddress>
</RBdetails>
</testApplication>
</testApplications>

linq to xml navigate through xml c#

I have some XML and need to be able to read the data within.
A sample of the XML is
<?xml version="1.0" ?>
<ConsumeLeadRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<LeadType>Mortgage</LeadType>
<LeadXml>
<ns1:LeadAssigned xmlns:ns1="http://YaddaYadda" xmlns:ns0="http://YaddaYadda" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns0:Lead>
<Reference>1234</Reference>
<Product>
<Mnemonic>Mortgage</Mnemonic>
<Description>Mortgage Leads</Description>
<SubType>Other</SubType>
</Product>
<ExtendedInfo>
<Mortgage>
<MortgageValue>75000</MortgageValue>
<MortgageValueLowerBound>1</MortgageValueLowerBound>
<MortgageValueUpperBound>500</MortgageValueUpperBound>
<PropertyValue>100000</PropertyValue>
<PropertyValueLowerBound>1</PropertyValueLowerBound>
<PropertyValueUpperBound>500</PropertyValueUpperBound>
<Adverse>false</Adverse>
<FirstTime>false</FirstTime>
</Mortgage>
</ExtendedInfo>
<Applicants>
<Applicant1>
<Title>Mr</Title>
<Forename>SampleForename</Forename>
<Surname>SampleSurname</Surname>
<DateOfBirth>1903-02-01</DateOfBirth>
<Smoker>false</Smoker>
<TelephoneNumbers>
<TelephoneNumber>
<Number>01244123456</Number>
<Type>Mobile</Type>
</TelephoneNumber>
</TelephoneNumbers>
<EmailAddresses>
<EmailAddress>
<Email>test#moneysupermarket.com</Email>
<Type>Business</Type>
</EmailAddress>
</EmailAddresses>
<Addresses>
<Address>
<Street>Sample Street</Street>
<District>Sample District</District>
<Town>Sample Town</Town>
<County>Sample County</County>
<Postcode>CH53UZ</Postcode>
<Type>Home</Type>
</Address>
</Addresses>
</Applicant1>
</Applicants>
</ns0:Lead>
<Assignment>
<Price>20</Price>
<AssignmentDateTime>2010-02-01T00:00:00</AssignmentDateTime>
<Subscription>
<Reference>1234</Reference>
<Subscriber>
<Title>Mr</Title>
<Forename>SampleForename</Forename>
<Surname>SampleSurname</Surname>
</Subscriber>
</Subscription>
<Account>
<Reference>1234</Reference>
<CompanyName>Sample Company</CompanyName>
</Account>
<LeadType>SampleLeadType</LeadType>
<TerritoryName>UNITED KINGDOM</TerritoryName>
</Assignment>
</ns1:LeadAssigned>
</LeadXml>
<AuthenticationUsername>Username</AuthenticationUsername>
<AuthenticationPassword>Password</AuthenticationPassword>
</ConsumeLeadRequest>
Using Linq to XML how do i navigate to the items?
Thanks
Sp
I have tried a few things like
XDocument Leads = XDocument.Load(#"C:\Users\Steven.Pentleton\AppData\Local\Temporary Projects\PAALeadImport\PAAExmple.xml");
var Lead = (from L in Leads.Descendants("Lead")
select new { LeadType = (string)L.Element("Reference") }).ToList();
var S = Lead.First();
string T = S.LeadType;
Are you looking for XDcoument or XElement in linq
Namespace: using System.Xml.Linq;
I guess you are looking for a Linq To Xml guide

Categories

Resources