Transform file to replace the whole parent node based on the text value of the child node - XML Transform

470 views Asked by At

I need to identify the text value of the child node element.

Purpose:

I want to create Transform file for an XML file so i need to replace the parent node Connection by comparing the value of the child node ClientKey

My XML File:

<Connection>
     <ClientKey>Client1</ClientKey>
     <ConnectionString>Test</ConnectionString>
     <WorkingDocs>Test</WorkingDocs>
     <TemplateDocs>Test</TemplateDocs>
     <PatientDocs>Test</PatientDocs>
     <ClientName>Test</ClientName>
     <ClientTimeZone>Test</ClientTimeZone>
     <ClientTimeDiff>Test</ClientTimeDiff>
     <ExceptionLogPath>Test</ExceptionLogPath>
</Connection>

How i can idendify the text of the ClientKey node

2

There are 2 answers

0
Chandramouli On BEST ANSWER

After googling i have found the solution for Config Transform in this case

We have different approaches

1. Condition(ClientKey/text()='Client1')
2. XPath(/Connections/Connection[ClientKey/text()='UHG_LOCAL'])

<Connection xdt:Transform="Replace" xdt:Locator="Condition(ClientKey/text()='Client1')">
    <ClientKey>GC_LOCAL</ClientKey>
    <ConnectionString>Test1</ConnectionString>
    <WorkingDocs>Test1</WorkingDocs>
    <TemplateDocs>Test1</TemplateDocs>
    <PatientDocs>Test1</PatientDocs>
    <ClientName>Test1</ClientName>
    <ClientTimeZone>Test1</ClientTimeZone>
    <ClientTimeDiff>Test1</ClientTimeDiff>
    <ExceptionLogPath>Test1</ExceptionLogPath>
</Connection>
1
Lingam On

Understanding LINQ to XML can be of more use.. Please check out https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/linq-to-xml-overview

XML values can be stored under "Elements" or "Attributes".. Consider below xml file..

<Connection>
 <ClientKey Name = "KeyName" >Client1</ClientKey>
 <ConnectionString>Test</ConnectionString>
 <WorkingDocs>Test</WorkingDocs>
 <TemplateDocs>Test</TemplateDocs>
 <PatientDocs>Test</PatientDocs>
 <ClientName>Test</ClientName>
 <ClientTimeZone>Test</ClientTimeZone>
 <ClientTimeDiff>Test</ClientTimeDiff>
 <ExceptionLogPath>Test</ExceptionLogPath>

XElement Data = XElement.Load() //Your Xml reference here

  1. To obtain Element value: (client key is the element)

String result = data.Element("ClientKey").value

  1. To obtain Attribute value: (Attribute is the Name property inside ClientKey)

String result = data.Attribute("Name").value