Linq to XML使用可重复节点CRUD操作

时间:2013-12-10 05:40:17

标签: asp.net-mvc linq-to-xml crud

我有一个像这样的xml:

<Root>
 <MortgaginContracts>
   <ContractInfo>
       <PledgeType>3</PledgeType>
       <ContractType>0</ContractType>
       <ContractNum>123</ContractNum>
   </ContractInfo>
   <ContractInfo>
       <PledgeType>4</PledgeType>
       <ContractType>3</ContractType>
       <ContractNum>125</ContractNum>
   </ContractInfo>
   <ContractInfo>
       <PledgeType>3</PledgeType>
       <ContractType>0</ContractType>
       <ContractNum>123</ContractNum>           
   </ContractInfo>
 </MorgaginContracts>
</Root>

没有可重复节点的标识。如何在MVC项目中为“ContractInfo”创建一个具有CRUD操作的存储库? ContractInfo可能有你的可重复子节点。

有什么想法吗?如何解决许多分层的xmlnodes?

1 个答案:

答案 0 :(得分:0)

我不明白这一点“而且ContractInfo可能有你的可重复子节点”

如果你想用xml进行CRUD操作,

using System.Xml.Linq; //Name space 

public class ContractInfo // Class for opertion - type
{
  public int PledgeType {get; set;}
  public int ContractType {get; set;}
  public int ContractNum {get; set;}
}

public class Operations
{
  public void insertContractInfo(ContractInfo obj)
  {
     XDocument contInfo = XDocument.load(HttpContext.Current.Server.MapPath("~/XMLFiles/contractInfo.xml"));


     contInfo.Root.Add(new XElement("ContractInfo",
           new XElement("PledgeType", obj.PledgeType),
           new XElement("ContractType", obj.ContractType),
           new XElement("ContractNum", obj.ContractNum)
           ));
    contInfo.Save(HttpContext.Current.Server.MapPath("~/XMLFiles/Appointments.xml"));
    string status = "success";
  }
}

这只是让你工作的一段代码示例。这很有效。对于编辑和更新,您可能需要使用元素(“节点名称”)。值