需求如下:
<?xml version="1.0">
<ListSection>
<ListPart>
<ListNo>1</ListNo>
<ListSymbol>test1</ListSymbol>
<ListComment>test1Comment</ListComment>
</ListPart>
<ListPart>
<ListNo>2</ListNo>
<ListSymbol>test2</ListSymbol>
<ListComment>test2Comment</ListComment>
</ListPart></ListSection>xXDocument xmlSource = XDocument.Load(new StringReader(strXml));
想通过xmlSource 给ListSymbol=test2的节点追加一个属性并附上值,即<ListSymbol attr="hello">test2</ListSymbol>
如何做呢,请教大家帮帮忙。谢谢
<?xml version="1.0">
<ListSection>
<ListPart>
<ListNo>1</ListNo>
<ListSymbol>test1</ListSymbol>
<ListComment>test1Comment</ListComment>
</ListPart>
<ListPart>
<ListNo>2</ListNo>
<ListSymbol>test2</ListSymbol>
<ListComment>test2Comment</ListComment>
</ListPart></ListSection>xXDocument xmlSource = XDocument.Load(new StringReader(strXml));
想通过xmlSource 给ListSymbol=test2的节点追加一个属性并附上值,即<ListSymbol attr="hello">test2</ListSymbol>
如何做呢,请教大家帮帮忙。谢谢
解决方案 »
- winform调试的时候,program.cs里的调用其他类的static 方法竟然没有初始化
- 用一个变量可不可以实现500的阶层 在 windows 易用程序中
- topmost窗体与messagebox冲突的问题
- 如何遍历一个HashTable?
- webservice不能返回hashtable或者是nameValueCollection吗
- C# 中的内存流(MemoryStream)使用问题
- 比较两个DataTable
- c#调用oracle存储过程的问题
- xml致命一击,我已经不堪憔悴,望神助!xml中使用html内容!
- 一个算法问题。
- 无法在 DLL中找到名为“ENinitenv”的入口点
- textBox的问题 高手解答我一下 谢谢!!
// 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;
}
}
var document = XDocument.Load("XMLFile1.xml"); var query = from ele in document.Descendants(XName.Get("ListSymbol"))
where ele.Value == "test2"
select ele;
var node = query.SingleOrDefault();
if (node != null)
{
node.Add(new XAttribute("attr", "hello"));
} document.Save("XmlResult.xml");
XmlResult.xml:<?xml version="1.0" encoding="utf-8"?>
<ListSection>
<ListPart>
<ListNo>1</ListNo>
<ListSymbol>test1</ListSymbol>
<ListComment>test1Comment</ListComment>
</ListPart>
<ListPart>
<ListNo>2</ListNo>
<ListSymbol attr="hello">test2</ListSymbol>
<ListComment>test2Comment</ListComment>
</ListPart>
</ListSection>
用linq to xml 爽.