2014-10-31 94 views
0

海的朋友,我需要与节点属性更新XML文件 我的XML结构如何更新使用LINQ XML节点

<BankName BankName="jinesh" TemplateModel="sam"> 
<ChqBasics> 
    <ChqL>30</ChqL> 
    <ChqW>50</ChqW> 
    <ChqImgPath>hai</ChqImgPath> 
</ChqBasics> 
<XandYPosition> 
    <column Name="ChqDate" X="10" Y="10" /> 
    <column Name="CPayAgainst" X="10" Y="10" /> 
    <column Name="ChqAmtDgt" X="10" Y="10" /> 
    <column Name="ChqAmtWrds" X="10" Y="10" /> 
</XandYPosition> 

我需要更新的XandYPosition节点元素所以我为此创建了一个功能,但我无法完成此操作。请帮助我实现此目的。

public static void updatenode(string bankname, string templatemodel,string field,string x,string y) 
    { 
     XDocument doc = XDocument.Load("newtest.xml"); 
     var updatenode = doc 
        .Descendants("BankName") 
        .Where(item => item.Attribute("BankName").Value == bankname && item.Attribute("TemplateModel").Value == templatemodel) 
        .Select(XandYPosition => XandYPosition.Descendants("XandYPosition").Descendants()); 
    } 

函数调用会是这样

BasicClass.updatenode(comboBox1.Text, comboBox2.Text, "ChqDate", "1000", "2000"); 

请帮助使代码完整

UPADTE: 我怎样才能更新BANKNAME = “Jinesh” 与 “XYZ”

+0

你想在这个XML文件以更新什么? – Vishal 2014-10-31 18:03:56

+0

to 1000 and 2000 – 2014-10-31 18:07:52

回答

1

试试这个代码,如果您收到错误,请随时询问:

public static void updatenode(string bankname, string templatemodel,string field,string X,string Y) 
{ 
    XDocument xDoc = XDocument.Load("../../newTest.xml"); 

    IEnumerable<XElement> updatenode = xDoc.Descendants("BankName") 
              .Where(x => x.Attribute("BankName").Value == bankname && x.Attribute("TemplateModel").Value == templatemodel) 
              .Select(x => x.Element("XandYPosition").Elements("column")).FirstOrDefault(); 

    updatenode.Where(x => x.Attribute("Name").Value == field).FirstOrDefault().Attribute("X").Value = X; 
    updatenode.Where(x => x.Attribute("Name").Value == field).FirstOrDefault().Attribute("Y").Value = Y; 

    xDoc.Save("../../newTest.xml"); 
} 

注意:

用您的xml文件的路径替换../../newTest.xml

更新:

XDocument xDoc = XDocument.Load("../../newTest.xml"); 

XElement updatenode = xDoc.Descendants("BankName") 
             .Where(x => x.Attribute("BankName").Value == "jinesh" && x.Attribute("TemplateModel").Value == "sam") 
             .Select(x => x.Element("ChqBasics").Element("ChqL")).FirstOrDefault(); 

updatenode.Value = "130"; 

xDoc.Save("../../newTest.xml"); 

更多引用请观看此YouTube频道的这些视频:

https://www.youtube.com/playlist?list=PL6n9fhu94yhX-U0Ruy_4eIG8umikVmBrk

+0

Thanks .... ok我会尽力让你知道 – 2014-10-31 18:19:26

+0

我得到这个错误Error ' System.Collections.Generic.IEnumerable '不包含'Attribute'的定义,也没有接受类型为'System.Collections.Generic.IEnumerable '可以找到(你是否缺少使用指令或程序集引用?) – 2014-10-31 18:25:32

+0

@JineshSam我已经更新了我的答案。 – Vishal 2014-10-31 18:35:57