在XMLDocument的子元素中添加属性 - C#

时间:2014-04-08 06:27:38

标签: c# xmldocument

我无法获得预期的结果。看看我的C#代码我正在添加第二个属性 “xsi:noNamespaceSchemaLocation”,但在outerXml中缺少单词“xsi:”。我失败的地方?

c#:

   XmlDocument doc = new XmlDocument();
   using (XmlWriter writer = doc.CreateNavigator().AppendChild())
    {
        new XmlSerializer(oWrite.GetType()).Serialize(writer, oWrite);
    }
   doc.DocumentElement.RemoveAllAttributes() ;
   XmlAttribute xmlAtri1,xmlAtri2;         
   xmlAtri1 = doc.CreateAttribute("xmlns:xsi");
   xmlAtri1.Value = "http://www.w3.org/2001/XMLSchema-instance";  
   doc.FirstChild.FirstChild.Attributes.Append(xmlAtri1);
   xmlAtri2 = doc.CreateAttribute("xsi:noNamespaceSchemaLocation");
   xmlAtri2.Value = "../xsd/nikuxog_customObjectInstance.xsd";
   doc.FirstChild.FirstChild.Attributes.Append(xmlAtri2);          
   return doc.DocumentElement  ;

外部XML:

<WriteCustomObjectInstance>
  <NikuDataBus xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" noNamespaceSchemaLocation="../xsd/nikuxog_customObjectInstance.xsd">
    <Header externalSource="NIKU" version="13.1.0.0248" />
    <customObjectInstances objectCode="web_req">
    </customObjectInstances>
  </NikuDataBus>
</WriteCustomObjectInstance>

预期的XML:

<WriteCustomObjectInstance>
   <NikuDataBus xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../xsd/nikuxog_customObjectInstance.xsd">
    <Header externalSource="NIKU" version="13.1.0.0248" />
    <customObjectInstances objectCode="web_req">
    </customObjectInstances>
  </NikuDataBus>
</WriteCustomObjectInstance>

谢谢,
JP

1 个答案:

答案 0 :(得分:0)

试试这个 -

   doc.DocumentElement.RemoveAllAttributes() ;
   var xsi = "http://www.w3.org/2001/XMLSchema-instance";
   XmlAttribute xmlAtri1;         
   xmlAtri1 = doc.CreateAttribute("xmlns:xsi");
   xmlAtri1.Value = xsi;  
   doc.FirstChild.FirstChild.Attributes.Append(xmlAtri1);
   xmlAtri1 = doc.CreateAttribute("noNamespaceSchemaLocation", xsi);
   xmlAtri1.Value = "../xsd/nikuxog_customObjectInstance.xsd";
   doc.FirstChild.FirstChild.Attributes.Append(xmlAtri1); 

有关详细信息,请查看此链接 -

Creating XMLDocument throguh code in asp.net