【问题标题】:How to create xml nodes with colon如何使用冒号创建 xml 节点
【发布时间】:2016-08-01 08:30:52
【问题描述】:

我想要一个如下的 xml 输出

  <ExtendedData xmlns:section="http://svr:1245/contact/kml/section.xsd">
    <section:secid>svr_01</section:secid>
    <section:name>test</unit:name>
  </ExtendedData>

我怎样才能做到这一点?我的代码如下,但输出不正确

var attribute = xDoc.CreateAttribute("section","secid","http://svr:1245/contact/kml/section.xsd");

XmlElement elementExtendedData = xDoc.CreateElement("ExtendedData");
elementPlacemark.AppendChild(elementExtendedData);

var elementSectionid = xDoc.CreateElement("section", "secid");
attribute.InnerText = UniqueID;
elementSectionid.Attributes.Append(attribute);
elementExtendedData.AppendChild(elementSectionid); 

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    首先,创建ElementData 元素添加命名空间前缀xmlns:section。然后使用正确的前缀和命名空间添加您的元素。

    var extendedData = xDoc.CreateElement("ExtendedData");
    extendedData.SetAttribute("xmlns:section", "http://svr:1245/contact/kml/section.xsd");
    
    elementPlacemark.AppendChild(extendedData);
    
    var secId = xDoc.CreateElement("section", "secid", "http://svr:1245/contact/kml/section.xsd");
    secId.InnerText = "svr_01";
    
    extendedData.AppendChild(secId);
    

    如果您可以选择,我建议您改用 LINQ to XML,这样使用起来会更好:

    XNamespace ns = "http://svr:1245/contact/kml/section.xsd";
    
    var element = new XElement("ExtendedData",
        new XAttribute(XNamespace.Xmlns + "section", ns),
        new XElement(ns + "secid", "svr_01")
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 2013-11-25
      • 2010-11-14
      • 2012-12-20
      • 2012-03-10
      • 1970-01-01
      相关资源
      最近更新 更多