我有多个元素和属性。我只想读几列。从下面的代码,我只想阅读值和评论。排除类型,mimetype和空格。
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
这是我用来读取文件的代码,但它显示的类型,mimetype和空格我不想要这些额外的列。我该怎么做
C#代码
#region this is the method that load the file to the grid
public void load()
{
try
{
oDataSet = new DataSet();
oDataTable = new DataTable();
//there must always be a file selected
if (txtInputfile.Text.Length > 0)
{
PathSelection = txtInputfile.Text;
}
//now adding the rows
foreach (DataGridViewColumn C in Gridview_Input.Columns)
{
oDataTable.Columns.Add(C.DataPropertyName, C.ValueType);
}
foreach (DataGridView _Row in Gridview_Input.Rows)
{
DataRow row1 = oDataTable.NewRow();
for (int i = 0; i < Gridview_Input.ColumnCount; i++)
{
oDataTable.Rows.Add(row1);
}
}
//here am transfering the datatable to the dataset
oDataSet.Tables.Add(oDataTable);
}
浏览要加载的文件的按钮
private void btnBrowse1_Click(object sender, EventArgs e)
{
try
{
BrowseFile();
//this method loads the file
load();
oDataSet = new DataSet();
//now am reading the files fro the path that is selected
oDataSet.ReadXml(PathSelection);
Gridview_Input.DataSource = oDataSet;
Gridview_Input.DataMember = "Data";
}
catch (Exception ex)
{
MessageBox.Show("Error occured.\nError message: " + ex.Message, "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
感谢您的帮助!
答案 0 :(得分:0)
您可以使用您想要使用的变量创建一个对象,然后从xml中读取并在阅读时只使用您需要的值填充List
修改强>
例如: 我想你知道如何创建一个类,我用来从xml读取值到List的方法是这样的:
List<YourClass> objectForValuesAndComments=new List<YourClass>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\Location To XML\File.xml");
foreach (XmlNode subnode in xmlDoc.DocumentElement.ChildNodes)
{
YourClass objectToInsert=new YourClass();
foreacht(XmlNode SubSubNode in subnode.ChildNodes)
{
if (SubSubNode.Name == "value")
{
objectToInsert.Value = SubSubNode.InnerText;
}
else if (SubSubNode.Name == "comment")
{
objectToInsert.Comment= SubSubNode.InnerText;
}
}
objectForValuesAndComments.Add(objectToInsert);
}
您可以在调试时进行修改,看看哪种方式最适合您:) 希望它有所帮助。