而不是循环需要一种在xml中设置节点列表值的方便方法

时间:2013-02-20 04:27:37

标签: c# xml xml-parsing

我有以下xml,我的需求是在每个ROW中设置WF_PROCESSID而不用c#中的循环和设置。请问有人建议解决方案吗?

<RESP_WF_MAP>
 <ROW>
  <PLAN_FOR_RESP>Mombasa</PLAN_FOR_RESP> 
  <WF_PROCESSID>-9999</WF_PROCESSID> 
  <WF_PROCESSNAME /> 
  <DIRECT_MAP_YN>N</DIRECT_MAP_YN> 
  </ROW>
  <ROW>
  <PLAN_FOR_RESP>Mombasa-Changamwe Branch</PLAN_FOR_RESP> 
  <WF_PROCESSID>-9999</WF_PROCESSID> 
  <WF_PROCESSNAME /> 
  <DIRECT_MAP_YN>N</DIRECT_MAP_YN> 
  </ROW>
  <ROW>
  <PLAN_FOR_RESP>Mombasa-Mombasa Branch</PLAN_FOR_RESP> 
  <WF_PROCESSID /> 
  <WF_PROCESSNAME /> 
  <DIRECT_MAP_YN>N</DIRECT_MAP_YN> 
  </ROW>
</RESP_WF_MAP>

我想消除这个循环,需要一个方便的xml处理方法

for ( intIndex = 0 ; intIndex < intLength ; intIndex++ )
{
    xmlRowElement           = (XmlElement)xmlRowNodeList.Item(intIndex);
    strWorkFlowId           = DwXMLUtilBO.getElementTagValue(xmlRowElement,"WF_PROCESSID");  // Customized static method to acquire the element value

    if(strWorkFlowId.Trim().Equals(""))
    {
       DwXMLUtilBO.setElementTagValue(xmlRowElement,"WF_PROCESSID" ,strWfId); // Customized static method to set the element value
    }

}

2 个答案:

答案 0 :(得分:0)

LINQ to XML:

foreach (var rowElement in XDocument.Load("yourXml").Descendants("ROW"))
{
    var idElement = rowElement.Element("WF_PROCESSID");
    if (string.IsNullOrWhiteSpace(idElement.Value))
    {
        idElement.Value = strWfId;
    }
}

答案 1 :(得分:0)

尝试使用XmlDocument类而不是您的自定义类,如下所示:

            var xml = @"
<RESP_WF_MAP>
<ROW>
<PLAN_FOR_RESP>Mombasa</PLAN_FOR_RESP> 
<WF_PROCESSID>-9999</WF_PROCESSID> 
<WF_PROCESSNAME /> 
<DIRECT_MAP_YN>N</DIRECT_MAP_YN> 
</ROW>
<ROW>
<PLAN_FOR_RESP>Mombasa-Changamwe Branch</PLAN_FOR_RESP> 
<WF_PROCESSID>-9999</WF_PROCESSID> 
<WF_PROCESSNAME /> 
<DIRECT_MAP_YN>N</DIRECT_MAP_YN> 
</ROW>
<ROW>
<PLAN_FOR_RESP>Mombasa-Mombasa Branch</PLAN_FOR_RESP> 
<WF_PROCESSID /> 
<WF_PROCESSNAME /> 
<DIRECT_MAP_YN>N</DIRECT_MAP_YN> 
</ROW>
</RESP_WF_MAP>";

        var doc = new XmlDocument();
        doc.LoadXml(xml);
        var list = doc.GetElementsByTagName("WF_PROCESSID");

        foreach (XmlNode node in list) 
        {
            node.InnerText = "your new value";
        }

        Console.Write(doc.InnerXml);
        Console.ReadKey();