2011-12-19 93 views
0

使用.NET,我將如何得到並在XML代碼中設置參數「sz2ndItemNumber」以下(獲得應在本例中返回PART123如下):訪問參數在XML通過.NET

<?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> 

謝謝, 埃裏克

回答

1

使用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(); 

    // . . . 
}