转一个在C#中为XML节点添加属性的方法 // 设定根节点ItemsCount属性值 // Parameter: // RootNodeName:根节点名称 // ds:数据集 // Return: // XmlDataDocument private XmlDataDocument SetItemsCountAttribute( string strRootNodeName, DataSet ds) ... { try ...{ XmlDataDocument xmlDoc; int ItemCount = 0; ds.DataSetName = strRootNodeName; ds.EnforceConstraints = false; if (ds.Tables.Count == 0) ...{ xmlDoc = new XmlDataDocument(); string xml = "<" + strRootNodeName + "></" + strRootNodeName + ">"; xmlDoc.LoadXml(xml); } else ...{ ds.Tables[0].TableName = "Item"; ItemCount = ds.Tables[0].Rows.Count; if (ItemCount == 0) ...{ xmlDoc = new XmlDataDocument(); string xml = "<" + strRootNodeName + "></" + strRootNodeName + ">"; xmlDoc.LoadXml(xml); } else ...{ xmlDoc = new XmlDataDocument(ds); } } XmlNode root = xmlDoc.FirstChild; // 创建节点 XmlNode attrCount = xmlDoc.CreateNode(XmlNodeType.Attribute, "ItemsCount", null); attrCount.Value = ItemCount.ToString(); // 添加节点属性 root.Attributes.SetNamedItem(attrCount); return xmlDoc; } catch (Exception e) ...{ string strMsg = e.Message; return null; } }