<?xml version="1.0" standalone="yes"?>
<Subject>
<Book>
<Name>ASP.NET</Name>
<Author>ABC</Author>
<Published>2018</Published>
<Price>$100</Price>
</Book>
</Subject>
以上是我的xml文件,我需要在C#中使用Windows Forms在Messsage Box中显示这些值而不编辑xml文件,在代码中我不想使用XML节点,如(名称,价。)。
修改
到目前为止我尝试过:
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNodeList xmlnode;
int i = 0;
string str = null;
FileStream fs = new FileStream(
@"C:\\Users\\15034\\Desktop\\Book.xml",
FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName("Book");
for (i = 0; i <= xmlnode.Count - 1; i++)
{
xmlnode[i].ChildNodes.Item(0).InnerText.Trim();
str = xmlnode[i].ChildNodes.Item(0).InnerText.Trim();
MessageBox.Show(str);
}
输出应如下所示:
ASP.NET
ABC
2018
$100
答案 0 :(得分:0)
您可以按如下方式使用DataGridview:
private void Display_Data(object sender, EventArgs e)
{
try
{
XmlReader xmlFile ;
xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
DataSet ds = new DataSet();
ds.ReadXml(xmlFile);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
可以在消息框中显示使用以下内容:
private void Display_Message(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML|*.xml";
if ( ofd.ShowDialog() == DialogResult.OK)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(ofd.FileName);
MessageBox.Show(xDoc.SelectSingleNode("FATCAFileErrorNotification/NotificationContentTxt").InnerText);
}
答案 1 :(得分:0)
您可以使用XDocument轻松完成:
var doc = XDocument.Load(yourxmlfile);
//Preparing string in readable format
var result = (from att in doc.Descendants("Book")
select
string.Format("Name: {0}", att.Element("Name").Value) + Environment.NewLine +
string.Format("Author: {0}", att.Element("Author").Value) + Environment.NewLine +
string.Format("Published: {0}", att.Element("Published").Value) + Environment.NewLine +
string.Format("Price: {0}", att.Element("Price").Value));
//Joining the result from XML
var message = string.Join(Environment.NewLine, result.ToArray());
MessageBox.Show(message);
正如@stuartd在评论中已经提到的那样,你的xml无效,在结束标记中缺少。
答案 2 :(得分:0)
使用XmlDocument:
XmlDocument xmldoc = new XmlDocument();
XmlNodeList xmlnode;
int i = 0;
string str = null;
FileStream fs = new FileStream(@"Books.xml", FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName("Book");
for (i = 0; i <= xmlnode.Count - 1; i++)
{
for (int j = 0; j <= xmlnode[i].ChildNodes.Count-1; j++)
{
if (xmlnode[i].ChildNodes.Item(j).Name == "Name")
continue;
xmlnode[i].ChildNodes.Item(j).InnerText.Trim();
str = xmlnode[i].ChildNodes.Item(j).InnerText.Trim();
MessageBox.Show(str);
}
}
使用XPath:
XPathDocument docNav = new XPathDocument("Books.xml");
XPathNavigator nav = docNav.CreateNavigator();
foreach (var item in nav.Select(@"/Subjects/Book/Author"))
{
MessageBox.Show(item.ToString());
}