Solved

How cam I xtract xml content into a new stream

Posted on 2012-12-31
8
480 Views
Last Modified: 2013-01-02
Hello all
Below is a complete xml file. I would like to extract the following tag <SearchResults> and all it's content into a new stream using c#
Note I DO NOT want  <SearchResults xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> tag
I WANT <SearchResults> and all it's contents
Sorry if I was rude in using capitals!!!

Here goes the xml:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <VacancyDetailsResponse xmlns="http://Navms.Ms.ExternalInterfaces/2011">
      <MessageId>8d947e6f-f3c2-46b5-a8e9-2d7f397fb186</MessageId>
      <SearchResults xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <AVMSHeader>
          <ApprenticeshipVacanciesDescription>If you are interested in finding out more about employing apprentices, the benefits they can bring to your business, and the benefits of Apprenticeship vacancies please visit our website and complete the online enquiry form.</ApprenticeshipVacanciesDescription>
          <ApprenticeshipVacanciesURL>http:\\www.apprenticeshipvacancies.gov.uk\Employers.aspx</ApprenticeshipVacanciesURL>
        </AVMSHeader>
        <SearchResults>
          <VacancyFullData>
            <VacancyLocationType>Standard</VacancyLocationType>
            <VacancyAddress>
              <AddressLine1>Kelvin Place</AddressLine1>
              <AddressLine2/>
              <AddressLine3/>
              <AddressLine4/>
              <AddressLine5/>
              <County>Norfolk</County>
              <GridEastM>585823</GridEastM>
              <GridNorthM>281921</GridNorthM>
              <Latitude>52.4033195889</Latitude>
              <Longitude>0.7319373790</Longitude>
              <PostCode>IP24 3RR</PostCode>
              <Town>Thetford</Town>
            </VacancyAddress>
            <ApprenticeshipFramework>Process Manufacturing</ApprenticeshipFramework>
            <ClosingDate>2012-11-30T00:00:00</ClosingDate>
            <ShortDescription>Great opportunity to work for a successful company in Thetford as a Manufacturer / Machinist.</ShortDescription>
            <EmployerName>Polypads Limited</EmployerName>
            <LearningProviderName>Delivered by W S Training Ltd.</LearningProviderName>
            <NumberOfPositions>1</NumberOfPositions>
            <VacancyTitle>Manufacturer / Machinist</VacancyTitle>
            <CreatedDateTime>2012-10-02T09:07:59.023</CreatedDateTime>
            <VacancyReference>98571</VacancyReference>
            <VacancyType>IntermediateLevelApprenticeship</VacancyType>
            <VacancyUrl>https://apprenticeshipvacancymatchingservice.lsc.gov.uk/NAVMS/Forms/Vacancy/VacancyDetails.aspx?Query=WgjHmG7hReZCalVznA0EzjTdgvTfmmXSS787Cl2KUOjAF0b6anssFkf0eoS3q02D1QEkH6w2AGnOpwHWszd%2bSPVQQaoRu5gPdXVyZlziKMJg0bJb9PJ1Axze9JCU5Mu4OcsJCktAOaW0ztnbbmujGMflOqnj9KKyxb8M2gXAxGGG7lW2Qo6sW62SndaKjHslTWXkGR8nydthAigiaEXo8Nd05GmR0TdmqDXPXwbWsCE2nUu9d8UpfE3eZDds%2bLx3z5N34NtrO8hFbaXB%2fHmNXg%3d%3d</VacancyUrl>
            <FullDescription><![CDATA[A fantastic opportunity for a horse enthusiast to work in a fast growing industry.<br />Main Duties:<br /><ul><li>Cutting and preparation of materials </li><li>Sewing </li><li>Eyeletting </li><li>Packing </li><li>Quality checking </li></ul>]]></FullDescription>
            <SupplementaryQuestion1>How will you travel to work?</SupplementaryQuestion1>
            <SupplementaryQuestion2>Have you got any experience with horses?</SupplementaryQuestion2>
            <ContactPerson>Geminesse Curtis- Training &amp;Recruitment Administrator - 01473 604260 - gcurtis@wstraining.co.uk</ContactPerson>
            <EmployerDescription>Polypads manufacture horse tack and horse equipment for the equine industry. They sell to commercial and domestic customers. They currently employ 10 people.</EmployerDescription>
            <ExpectedDuration>15 months</ExpectedDuration>
            <FutureProspects>This is a fast growing company, and there is potential to grow with it. Increase work load and tasks as well as increasing responsibilities. &lt;br />&lt;br />Possibilities of becoming an experienced machinist. This is a permanent position.</FutureProspects>
            <InterviewFromDate>2012-06-04T00:00:00</InterviewFromDate>
            <LearningProviderDesc>WS Training offers apprenticeships in a wide variety of occupations. If you are interested in gaining a qualification while you work then contact us, whether you are already employed or need help finding a job. Apprenticeships allow you to "Earn While You Learn"</LearningProviderDesc>
            <LearningProviderSectorPassRate>67</LearningProviderSectorPassRate>
            <PersonalQualities><![CDATA[<ul><li>Horse knowledge essential </li><li>Able to work as part of a team </li></ul><p>?</p><p>?</p>]]></PersonalQualities>
            <PossibleStartDate>2012-06-11T00:00:00</PossibleStartDate>
            <QualificationRequired>Basic Literacy and Numeracy skills</QualificationRequired>
            <SkillsRequired><![CDATA[<ul><li>Good attention to detail </li><li>Experience using a sewing machine (desirable) </li></ul><p>?</p>]]></SkillsRequired>
            <TrainingToBeProvided>Level 2 in Manufacturing including technical certificate and key skills. This is a work based qualification and does not require day release to college.</TrainingToBeProvided>
            <WeeklyWage>100.0000</WeeklyWage>
            <WorkingWeek>Monday to Thursday 9am - 4:30pm</WorkingWeek>
            <OtherImportantInformation>From the 1st October 2010 a National Minimum Wage (NMW) for apprentices has been introduced for young people aged 16-18 and those aged over 19 in the first year of their Apprenticeship. The new rate is ?2.50 per hour. The new NMW applies to time working plus time spent training as this is also part of the Apprenticeship. Anyone not covered by the age category above will be entitled to the NMW appropriate to their age. &lt;br />&lt;br />Applications will be assessed and interviewed as soon as they are received, which may result in the vacancy closing before the advertised closing date, please apply as soon as possible to avoid disappointment.</OtherImportantInformation>
            <EmployerWebsite/>
          </VacancyFullData>        
        </SearchResults>
        <TotalPages>10</TotalPages>
      </SearchResults>
    </VacancyDetailsResponse>
  </s:Body>
</s:Envelope>


If anyone could make my New Year I would be ever in their debt
Thanks Puds 32
0
Comment
Question by:Puds32
  • 4
  • 2
  • 2
8 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 450 total points
ID: 38733613
You can try something along these lines:

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleApplication46
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument xdoc = XDocument.Load("input.xml");
            MemoryStream newStream = new MemoryStream();
            XNamespace i = "http://Navms.Ms.ExternalInterfaces/2011";
            IEnumerable<XElement> searchResults = xdoc.Descendants(i + "SearchResults")
                                                        .Descendants(i + "SearchResults");

            searchResults.First().Save(newStream);
        }
    }
}

Open in new window

0
 
LVL 8

Expert Comment

by:JustAndrei
ID: 38735193
Sorry for offtopic, why do you want to get rid of xmlns:i? It's just a declaration of an alias for the namespace, while the element itself does not belong to that namespace, so the declaration does not make your post-processing any harder.
0
 

Author Comment

by:Puds32
ID: 38736287
Hi sorry for the delay in replying
Thanks for the above help, I will give it a try later today and update you

As to the offtopic comment:
I am putting the fragment into a datatable which I will then staore to an sql database, this works fine and seems staright forward, but if I try loading the whole documnet into a datatable I get errors, I'm a bit new this and have chosen the path of least resistance!!!
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 38737092
@JustAndrei

Hopefully I'll be corrected if I am wrong  ; )

I initially thought he was trying to strip out the alias, but I looked a bit closer and there are actually two SearchResults elements--one a descendant of the other. The ancestor has the namespace declaration whereas the descendant does not. The code above reflects trying to get the descendant, not the ancestor.
0
 
LVL 8

Expert Comment

by:JustAndrei
ID: 38737673
Oh, I didn't notice there were two elements, so I thought Puds32 wanted to remove the declaration. Now it seems the descendant is needed indeed. Sorry, it's my mistake.
0
 
LVL 8

Assisted Solution

by:JustAndrei
JustAndrei earned 50 total points
ID: 38737700
Btw, kaufmed, I suspect your code may output namespace navms.ms... Doesn't it? (I haven't tried)
I'm asking because Puds32 seems to want to get rid of all namespaces.
0
 

Author Closing Comment

by:Puds32
ID: 38738574
Hi kaufmed
Your solution seems to have worked beautifully, the resulting xml fragment loaded into a datatable and that desplayed in a grid

Hi JustAndrei
You right it did include a namespace in the fragment, but this didn't seem to stop it loading into a datatable so I can live with it, if you know how to get rid of the namespace that would be good

Thanks to you both
Regards Puds32
0
 
LVL 8

Expert Comment

by:JustAndrei
ID: 38739167
foreach( var e in searchResults.First().DescendantsAndSelf() )
{
    e.Name = XNamespace.None.GetName( e.Name.LocalName );
}

Open in new window

0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question