Manipulating an XML file using VB.Net

I've got a .XML file (content of the file at the bottom of the question) and I need to edit certain aspects of it.  I can edit specific elements such as SenderID using

doc.GetElementsByTagName("SenderID")(0).InnerXml

but I'm struggling to find example code that would allow me to easily change the innertext of both the <Key Type="STORN">As advised by SDS Team</Key> elements.  i.e. I need to change "As advised by SDS Team" to something else.

Finally after completing the above changes I need to be able to edit all the innertext of most of the nodes following <SDLT> with ease...so examples of how to accomplish this would also be appreciated.

Hope this is clear, thanks in advance for any help

Simon

<?xml version="1.0" encoding="UTF-8"?>
<!-- PLEASE NOTE - This is an example to show the layout of a valid XML
test message for an SDLT submission.  V1.0 10 Jan 05  -->
<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope">
  <EnvelopeVersion>2.0</EnvelopeVersion>
  <Header>
    <MessageDetails>
      <Class>IR-SDLT-LTR</Class>
      <Qualifier>request</Qualifier>
      <Function>submit</Function>
      <CorrelationID />
      <Transformation>XML</Transformation>
      <GatewayTest>1</GatewayTest>
      <GatewayTimestamp />
    </MessageDetails>
    <SenderDetails>
      <IDAuthentication>
        <SenderID>MSD2058</SenderID>
        <Authentication>
          <Method>clear</Method>
          <Role>principal</Role>
          <Value>testing1</Value>
        </Authentication>
      </IDAuthentication>
    </SenderDetails>
  </Header>
  <GovTalkDetails>
    <Keys Type="1000002058">
      <Key Type="STORN">As advised by SDS Team</Key>
    </Keys>
    <TargetDetails>
      <Organisation>IR</Organisation>
    </TargetDetails>
    <ChannelRouting>
      <Channel>
        <URI>2058</URI>
        <Product>Themis</Product>
        <Version>0.0.1</Version>
      </Channel>
    </ChannelRouting>
  </GovTalkDetails>
  <Body>
    <IRenvelope xmlns="http://www.govtalk.gov.uk/taxation/SDLT">
      <IRheader>
        <TestMessage>0</TestMessage>
        <Keys>
          <Key Type="STORN">As advised by SDS Team</Key>
        </Keys>
        <PeriodEnd>2004-03-01</PeriodEnd>
        <DefaultCurrency>GBP</DefaultCurrency>
        <IRmark Type="generic">Include a valid IRmark here</IRmark>
        <Sender>Individual</Sender>
      </IRheader>
      <SDLT>
        <UTRN>153492288MT</UTRN>
        <TransactionDetails>
          <TransactionDescription>F</TransactionDescription>
          <EffectiveDate>2004-02-01</EffectiveDate>
          <RestrictionsAffecting Apply="no">
          </RestrictionsAffecting>
          <ContractDate>2004-02-01</ContractDate>
          <LandExchanged Exchanged="no">
          </LandExchanged>
          <PursuantToOption>no</PursuantToOption>
          <TaxCalculation>
            <ClaimingRelief Claiming="no">
            </ClaimingRelief>
            <Consideration>
              <TotalConsideration>100000.00</TotalConsideration>
              <FormCode>30</FormCode>
            </Consideration>
            <LinkedTransaction IsLinked="no">
            </LinkedTransaction>
            <TotalDue>1000.00</TotalDue>
            <AmountPaid IncludesPenalties="no">1000.00</AmountPaid>
          </TaxCalculation>
        </TransactionDetails>
        <LandDetail>
          <NumberOfProperties>1</NumberOfProperties>
          <Property>
            <PropertyType>01</PropertyType>
            <AddressOfLand AddressExtended="no">
              <PostCode>AA1 1AA</PostCode>
              <HouseNumber>100</HouseNumber>
              <Line>The Road</Line>
              <Line>The Town</Line>
            </AddressOfLand>
            <LAnumber>9051</LAnumber>
            <TitleNumber>AA11111</TitleNumber>
            <NLPGUPRN>111111222222</NLPGUPRN>
            <PlanSubmitted>no</PlanSubmitted>
            <InterestTransfered>FP</InterestTransfered>
          </Property>
        </LandDetail>
        <VendorDetails>
          <NumberOfVendors>1</NumberOfVendors>
          <Vendor>
            <Name>
              <Title>Mr</Title>
              <Forename>Tax</Forename>
              <CompanyOrSurname>Payer</CompanyOrSurname>
            </Name>
            <Address>
              <PostCode>AA1 1AA</PostCode>
              <HouseNumber>100</HouseNumber>
              <Line>The Road</Line>
              <Line>The Town</Line>
            </Address>
          </Vendor>
          <AgentDetails>
            <Name>Solicitor &amp; Co</Name>
            <Address>
              <PostCode>BB1 1BB</PostCode>
              <Line>The Office</Line>
              <Line>The Road</Line>
              <Line>The Town</Line>
            </Address>
            <DXnumber>11111 Town</DXnumber>
            <EmailAddress>a@a.co.uk</EmailAddress>
            <Reference>A1111/AA/AA</Reference>
            <Telephone>01111 11111</Telephone>
          </AgentDetails>
        </VendorDetails>
        <PurchaserDetails>
          <NumberOfPurchasers>1</NumberOfPurchasers>
          <Purchaser>
            <Name>
              <Title>Miss</Title>
              <Forename>Tax</Forename>
              <CompanyOrSurname>Payer</CompanyOrSurname>
            </Name>
            <SameAddressAsLand>yes</SameAddressAsLand>
            <NINO>AA111111A</NINO>
            <Trustee>no</Trustee>
            <VendorConnected>no</VendorConnected>
            <CertificateAddress>Agent</CertificateAddress>
            <AuthoriseAgent>yes</AuthoriseAgent>
            <AgentDetails>
              <Name>A Conveyancer</Name>
              <Address>
                <PostCode>AA1 2AB</PostCode>
                <HouseNumber>1</HouseNumber>
                <Line>A Road</Line>
                <Line>A Town</Line>
              </Address>
              <DXnumber>22222 Town</DXnumber>
              <Reference>A111/BB</Reference>
              <Telephone>02222 222222</Telephone>
            </AgentDetails>
          </Purchaser>
        </PurchaserDetails>
        <SupplementarySections>
          <SDLT2Count>0</SDLT2Count>
          <SDLT3Count>0</SDLT3Count>
          <SDLT4Count>0</SDLT4Count>
        </SupplementarySections>
      </SDLT>
    </IRenvelope>
  </Body>
</GovTalkMessage>
noel58Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

The_BiochemistCommented:
Check out this post, it should explain prety much everything about manipulating xml:

http://www.informit.com/articles/article.asp?p=23021&rl=1
noel58Author Commented:
Sorry to be a pain but could you give me a VB.Net code example in the context of the XML I have and the points I made initially.
Joe_GriffithCommented:
You should be able to do something like this:

doc.SelectSingleNode("//GovTalkDetails/Keys/Key").InnerText = "Foo"
doc.SelectSingleNode("//Body/IRenvelope/IRheader/Keys/Key").InnerText = "Bar"
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

noel58Author Commented:
Joe,

On the line of code you have given me used in this context I receieve the error "object reference not set to an instance of an object"  any ideas?

Dim doc As XmlDocument = New XmlDocument
doc.Load("C:\sdlt.xml")

doc.SelectSingleNode("//GovTalkDetails/Keys/Key").InnerText = "Foo"
doc.SelectSingleNode("//Body/IRenvelope/IRheader/Keys/Key").InnerText = "Bar"

doc.Save("C:\newsdlt.xml")

Joe_GriffithCommented:
I think you will get that error if the specified node doesn't exist.  Obviously it does if the strings are correct.  I typed them in by looking at your example but could easily have gotten one or both wrong. Check to make sure that I got the strings right if you just copied my code.

I use this technique a lot but I don't normally use attributes in my documents.  You may have to include the attribute in the string as well

noel58Author Commented:
The example XML code im using is exactly as per the layout you've got at the top but for some reason I still can't seem to get a handle on any of the nodes.  For example as per the documentation that came with this XML it says that the <SenderID> could be accessed using the XPath "GovTalkMessage/Header/SenderDetails/IDAuthentication/SenderID" .  

So based on that I used the following...

doc.SelectSingleNode("GovTalkMessage/Header/SenderDetails/IDAuthentication/SenderID").InnerText = "Bar"

However I'm still getting object not set to an instance of an object.  If I could get one working example of the above line of code based on the XML above I'd have enough to crack on with this...
Joe_GriffithCommented:
Try backing off to the top node:

doc.SelectSingleNode("GovTalkMessage").InnerText = "Bar"

or

doc.SelectSingleNode("//GovTalkMessage").InnerText = "Bar"

and see what you get.

noel58Author Commented:
How about this for weird...I used one of those programs that generates XPath queries for you (Stylus Studio XML Home Edition) and it gave me the following query to access \GovTalkMessage\Header\MessageDetails\Class

"/*[local-name()='GovTalkMessage']/*[local-name()='Header'][1]/*[local-name()='MessageDetails'][1]/*[local-name()='Class'][1]"

So I did the following...

doc.SelectSingleNode("/*[local-name()='GovTalkMessage']/*[local-name()='Header'][1]/*[local-name()='MessageDetails'][1]/*[local-name()='Class'][1]").InnerText = "WOWOWO"

And sure enough it updated the InnerText no problems.  However I tried the same program on a simple XML file, and it generated a simple Xpath query

"/bookstore/book[1]/title[1]"

Why does my XML (which although I can see is a bit more complicated isn't THAT bad) require such complicated Xpath query??
Joe_GriffithCommented:
This line: <GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope">
includes a name space specification.  The element names you see in the file are actually called "Local Names". There real names includes the name space as a prefix.

There is probably someway to set the namespace in XPath to avoid having to specify that you are serching only local names.

TaraChuckCommented:
Hi noel58,

It seems like you are wanting to pull all the SDLT info out of your db using vb.net, and insert it into your xml template doc?  Without intending to rain on any strawberries, this is perhaps a flawed method from the start, and you may end up re-writting your app anyway.

My Reasoning:

- The IR are very picky about their XML structures, and what data is, and is not acceptable.  
- I believe strings are output as utf-16, and the IR demand UTF-8 encoding.
- The IRmark node will have to be pulled out prior to processed, then reinserted back in with the relevant mark (..you tried creating one of them things yet??!)

etc etc etc... plus a hundred and one other reasons.

My advice?

Again I'm making assumptions.. you're not a commercial CMS provider from your previous posts by the looks...If your serious about writing this, start by exporting your data via an xslt.

If your patience (or time) is limited.. go commercial.  Bolt on's to case management systems will be out soon (the IR went live this month).


Tara.
noel58Author Commented:
Tara,

Very insightful advice.  I am a commercial CMS provider and what has got me is the lack of relevant support from the HMRC.  No relevant examples (other than an outdated VB 6 application), just piles and piles of specifications, busines validation rules etc.  I've asked them for a VB.Net example but nobody seems to be able to help me with that.

You mentioned bolt ons, who will be supplying these?  The HMRC or are third parties now getting involved?  Where would I find the IR bolt on?  

I know what you mean about xslt, I've dabbled in that but its really not something I would choose to get stuck in to if there are alternatives such as bolt ons.  The whole thing is a headache.  We've integrated with search companies, form providers, and many other applications but this one has got me!

Simon
TaraChuckCommented:

I can empathise with your concerns on the lack of support from the HMRC, as well as the amount of information supplied in the spec's.  I can't get over the fact that there are two business rule specs for the same set of data (barcoded forms and the online version).

There is a list of recognised suppliers for online support: http://www.hmrc.gov.uk/efiling/sdltsoft-dev.htm

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
noel58Author Commented:
Tara your comments have been most useful, I've decided to subcontract the whole job out to somebody who actually knows about XSLT and has the programming skills that I unfortunately don't!

Thanks for your help everyone.

Simon
TaraChuckCommented:
In a weird way it's good to see someone having the same struggles I faced - it means I'm not the enept developer I was leading myself to beleive!

Best of luck,
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.