如果节点已经存在,我需要添加几个子节点或更新该节点。从下面的小示例中可以看到,我有一个节点有一个子节点,另一个没有。假设我有一个来自这两个SQL表的定义,我想将这个值添加到节点中。
XML
<workbook>
<datasources>
<column datatype='real' name='[CONTRACT_PAYMENT_AMT]' role='measure' type='quantitative'>
<desc>
<formatted-text>
<run>The amount being paid on the contract.</run>
</formatted-text>
</desc>
</column>
<column datatype='real' name='[CONTRACT_PAYMENT_DATE]' role='measure' type='quantitative'>
</column>
</datasources>
下面是我必须得到name属性的代码。列是可能保存数据类型、名称、角色和类型的类。
IEnumerable<string> names = from Columns in XDocument.Load(path).Descendants("column")
select Columns.Attribute("name").Value;
foreach (string name in names)
{
}这是该方法的一个开端。
我很难思考如何存储值并更新XML,或者只是查看每个节点,然后在文档中更新。有什么想法吗?
编辑-新代码向当前运行节点添加新值,但不添加新的one..with定义。
var document = XDocument.Load(path);
var elements = (from column in document.Descendants("column")
select new
{
AttributeName = column.Attribute("name").Value,
Run = column.Descendants("run").FirstOrDefault() ?? new XElement("run")
}).ToList();
foreach (var item in elements)
{
if (item.Run == null) continue;
else
{
item.Run.Value = GetVariable(item.AttributeName);
// Getvariable is the method that returns the definition
}
}
document.Save(path);发布于 2015-11-11 20:39:11
您可以点出以下逻辑:
var document = XDocument.Load(path);
var elements = (from column in document.Descendants("column")
select new
{
AttributeName = column.Attribute("name").Value,
Parent = column,
Run = column.Descendants("run").FirstOrDefault()
}).ToList();
foreach(var item in elements)
{
XElement run;
if (item.Run == null)
{
run = new XElement("run");
item.Parent.Add(
new XElement("desc",
new XElement("formatted-text",
run
)
)
);
}
else
{
run = item.Run;
}
if(item.AttributeName == "BlaBlaOne")
{
run.Value = "Your definition here";
}
}
document.Save(path);https://stackoverflow.com/questions/33659093
复制相似问题