Eric Hartner
Eric Hartner

Reputation: 51

Accessing Parameters In XML Via .NET

Using .NET, how would I get and set the parameter 'sz2ndItemNumber' in the XML code below (get should return PART123 in the example below):

<?xml version='1.0' encoding='utf-8' ?>
<jdeRequest pwd='test123' type='callmethod' user='TESTUSER' session='' environment='DEVENV' sessionidle='120'>
<callMethod app='CSHARPTST' name='GetItemMasterBy2ndItem'>
    <returnCode code='0'/>
    <params>
        <param name='sz2ndItemNumber'>PART123</param>
        <param name='idF4101LongRowPtr'>0</param>
        <param name='cErrorCode'></param>
        <param name='cReturnPtr'></param>
        <param name='cSuppressErrorMsg'></param>
        <param name='szErrorMsgID'></param>
        <param name='szDescription1'></param>
        <param name='szDescription2'></param>
        <param name='mnShortItemNumber'>0</param>
        <param name='sz3rdItemNumber'></param>
        <param name='szItemFlashMessage'></param>
        <param name='szAlternateDesc1'></param>
        <param name='szAlternateDesc2'></param>
        <param name='szLngPref'></param>
        <param name='cLngPrefType'></param>
        <param name='szStandardUOMConversion'></param>
    </params>
</callMethod>
</jdeRequest>

Thank you, Eric

Upvotes: 0

Views: 98

Answers (1)

bobbymcr
bobbymcr

Reputation: 24167

Use LINQ to XML.

using System.Linq;
using System.Xml.Linq;

// . . .
string xml = @"<?xml version='1.0' encoding='utf-8' ?> ..."; 
// . . . rest of XML string omitted for brevity . . . 

// Read XML from string
XDocument document = XDocument.Parse(xml);

// Select the first matching 'param' element with the specified name
XElement paramElement = 
    (from p in document.Descendants("param")
    let a = p.Attribute("name")
    where a != null && a.Value == "sz2ndItemNumber"
    select p).FirstOrDefault();

if (paramElement != null)
{
    // Get the inner text
    string text = paramElement.Value;

    // Set the inner text
    paramElement.Value = "Something Else";

    // Get the new XML document text
    string newXml = document.ToString();

    // . . .
}

Upvotes: 1

Related Questions