如何使用c#创建xml

如何使用c#创建xml

本文介绍了如何使用c#创建xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





i想要像这样创建XML



 <  记录 >  
< FIELD ID = 1 MAX_LENGTH = 100 / >
< FIELD ID = 2 MAX_LE NGTH = 100 / >
< FIELD ID = 3 MAX_LENGTH = 7 / >
< FIELD ID = 4 MAX_LENGTH = 100 / >
< FIELD ID = 5 MAX_LENGTH = 100 / >
< / RECORD >
< ROW >
< COLUMN SOURCE = 3 NAME = Col1 / >
< COLUMN SOURCE = 2 NAME = Col2 / >
< COLUMN SOURCE = 1 NAME = Col3 / >
< COLUMN SOURCE = 4 NAME = Col4 / >
< / ROW > ;





这是我到目前为止所做的,但它在最后一行中的抛出错误为此文档已经有一个documentelement节点



 XmlDocument xmlDoc =  new  XmlDocument(); 
XmlElement rootNode = xmlDoc.CreateElement( RECORD);
xmlDoc.AppendChild(rootNode);

int dbIndex = 0 ;
foreach (ColumnMapping columnMapping in columnMappings)
{
XmlNode userNode = xmlDoc.CreateElement( FIELD);
XmlAttribute attribute = xmlDoc.CreateAttribute( ID);
attribute.Value = dbIndex.ToString();
userNode.Attributes.Append(attribute);
rootNode.AppendChild(userNode);
dbIndex ++;
}

rootNode = null ;
rootNode = xmlDoc.CreateElement( ROW);
xmlDoc.AppendChild(rootNode);
解决方案



hi,

i want to create XML like this

<RECORD>
  <FIELD ID="1"MAX_LENGTH="100" />
  <FIELD ID="2" MAX_LENGTH="100" />
  <FIELD ID="3" MAX_LENGTH="7"/>
  <FIELD ID="4" MAX_LENGTH="100"/>
  <FIELD ID="5" MAX_LENGTH="100"/>
 </RECORD>
 <ROW>
  <COLUMN SOURCE="3" NAME="Col1" />
  <COLUMN SOURCE="2" NAME="Col2" />
  <COLUMN SOURCE="1" NAME="Col3" />
  <COLUMN SOURCE="4" NAME="Col4" />
 </ROW>



This is what i have done so far, but its throwing error in the last line as "This document already has a documentelement node"

XmlDocument xmlDoc = new XmlDocument();
XmlElement rootNode = xmlDoc.CreateElement("RECORD");
xmlDoc.AppendChild(rootNode);

int dbIndex = 0;
foreach (ColumnMapping columnMapping in columnMappings)
{
  XmlNode userNode = xmlDoc.CreateElement("FIELD");
  XmlAttribute attribute = xmlDoc.CreateAttribute("ID");
  attribute.Value = dbIndex.ToString();
  userNode.Attributes.Append(attribute);
  rootNode.AppendChild(userNode);
  dbIndex++;
}

rootNode = null;
rootNode = xmlDoc.CreateElement("ROW");
xmlDoc.AppendChild(rootNode);
解决方案




这篇关于如何使用c#创建xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 22:20