Search code examples
xmlvb.netfilehandlestringwriter

Please tell me how to find and replace particular word in a file using vb.net


i have created a template xml file witch contain some words like {contentname}. i need to replace such a tags with my values. please tell me how to search such a words and replace using filehandling in vb.net my xml templatefile is like this:

<!-- BEGIN: main -->
<?xml version="1.0" encoding="UTF-8"?>
<OTA_HotelSearchRQ xmlns="http://www.opentravel.org/OTA/2003/05" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05OTA_HotelSearchRQ.xsd" EchoToken="{EchoToken}" Target="{Target}" Version="1.006" PrimaryLangID="{PrimaryLangId}" MaxResponses="{MaxResponses}">
<POS>
<!-- BEGIN:Source -->
<Source>
<RequestorID ID="{affiliateId}" MessagePassword="{MessagePassword}" />
</Source>
<!-- END:Source -->
</POS>
<Criteria <!-- BEGIN:AvailableOnlyIndicator -->AvailableOnlyIndicator="    {AvailableOnlyIndicator}"<!-- END:AvailableOnlyIndicator -->>
<Criterion>


Solution

  • If you have a valid XML file as template, you should follow one of two ways:

    • Open it as XmlDocument and update your values through DOM
    • Create a XSLT and pass your parameters to transform your template

    Below I'm talking about first method. I'll write C#, but you can easily translate it to VB.NET:

    XmlDocument doc = new XmlDocument();
    doc.Load("yourfile.xml");
    
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("ota", "http://www.opentravel.org/OTA/2003/05")
    
    XmlElement hotelSearch = doc.SelectSingleNode
        ("/ota:OTA_HotelSearchRQ", nsmgr) as XmlElement;
    hotelSearch.SetAttribute("EchoToken", "{EchoToken}");
    hotelSearch.SetAttribute("Target", "{Target}");
    // ... and so on ...
    
    XmlElement requestorId = hotelSearch.SelectSingleNode
        ("ota:POS/ota:Source/ota:RequestorID", nsmgr) as XmlElement;
    requestorId.SetAttribute("ID", "{affiliateId}");
    requestorId.SetAttribute("MessagePassword", "{MessagePassword}");
    // ... and so on ...