代码之家  ›  专栏  ›  技术社区  ›  Alex

使用Xelement从C设置XML嵌套节点

  •  1
  • Alex  · 技术社区  · 15 年前

    我正在修改一些遗留代码,需要用C解析/写入XML。我试图设置嵌套元素的值,但没有得到任何乐趣。这应该很简单,但我不知道我做错了什么。

    这是XML模板:

    <my:productReport>
        <my:productId>1</my:productId>
        <my:company>MyCompany</my:company>
        <my:productPerson>
            <my:productPersonId xsi:nil="true"></my:productPersonId>
            <my:productPersonName></my:productPersonName>
        </my:productedBy>
    </my:productReport>
    

    我可以让公司不必担心:

     XElement companyEle = doc.Root.Element(myNameSpace + "company");
       companyEle.Value = value;
    

    但如何添加产品人员ID和名称?可能要添加多个personid/personname元素。

    1 回复  |  直到 15 年前
        1
  •  2
  •   dugas    15 年前

    //Get collection of productPerson elements
    IEnumerable<XElement> prodPersons = productReport.Elements("productPerson");
    foreach(XElement pp in prodPersons)
    {
      //Set values
      pp.Element("productPersonId").Value = "1";
      pp.Element("productPersonName").Value = "xxx";
    }
    
    //Add a productPerson element
    XElement prodPersonEle =
         new XElement("productPerson",
              new XElement("productPersonId","3"),
              new XElement("productPersonName", "Somename")
         );
    
    
    //Add prodPersonEle to whatever parent it belongs.