通过.NET访问XML中的参数

时间:2011-12-19 02:41:18

标签: c# xml

使用.NET,我如何在下面的XML代码中获取和设置参数'sz2ndItemNumber'(获取应返回下面示例中的PART123):

<?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 个答案:

答案 0 :(得分: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();

    // . . .
}