使用变量标签读取XML文件

时间:2012-10-05 05:45:10

标签: c# asp.net xml

我已经按以下格式创建了一个XML文件:

<?xml version="1.0" encoding="utf-8" ?>
<Employee_Info>
<Employee>
<Name> Blah </Name>
<ID> 001 </ID>
<Dept> ISDC </Dept>
</Employee>
<Employee>
<Name> Bleh </Name>
<ID> 002 </ID>
<Dept> COE </Dept>
</Employee>
<Employee>
<Name> Bah </Name>
<ID> 003 </ID>
<Dept> Roll_Out </Dept>
</Employee>
</Employee_Info>

现在这是我用来显示数据的代码:

XmlTextReader reader = new XmlTextReader(Server.MapPath("~/XMLFile.xml"));
    while (reader.Read())
    {
        switch (reader.NodeType)
        {
            case XmlNodeType.Element: // The node is an element.
                Response.Write("<" + reader.Name + ">");
                break;
            case XmlNodeType.Text: //Display the text in each element.
                Response.Write(reader.Value + "<br />");
                break;
            case XmlNodeType.EndElement: //Display the end of the element.
                Response.Write("</" + reader.Name + ">");
                break;
        }
    }

现在我的输出结果如下:

Blah 
001 
ISDC 
Bleh 
002 
COE 
Bah 
003 
Roll_Out

如何显示标签以及值?那就是我希望我的输出格式如下:

Name: Blah
ID: 001
Dept: COE

如果我只在一个地方在XML文件中添加一个额外的元素,比如3个员工信息中的额外电子邮件标签,该怎么办?我怎么读?

4 个答案:

答案 0 :(得分:2)

XDocument doc = XDocument.Load(Server.MapPath("~/XMLFile.xml"));

var rows = doc.Descendants("Employee").Select(e => new
{
    Name = e.Element("Name").Value,
    ID = e.Element("ID").Value,
    Dept = e.Element("Dept").Value
});

foreach (var row in rows)
{
    Response.Write(String.Format("Name: {0} <br />", row.Name));
    Response.Write(String.Format("ID: {0} <br />", row.ID));
    Response.Write(String.Format("Dept: {0} <br />", row.Dept));
}

或没有硬编码:

foreach (XElement x in doc.Descendants("Employee").Nodes())
{
    Response.Write(String.Format("{0}: {1} <br />", x.Name, x.Value));
}

答案 1 :(得分:1)

为什么不使用LINQ to XML更简单:

 var result =  xDoc.Descendants("Employee").Select(x => new
                        {
                            Name = x.Element("Name").Value,
                            Id = x.Element("ID").Value,
                            Dept = x.Element("Dept").Value,
                        });

答案 2 :(得分:1)

请尝试以下代码。

XmlDocument xDoc = new XmlDocument();
xDoc.Load("Server.MapPath("~/XMLFile.xml")");

XmlNodeList nodeList;
nodeList = xDoc.DocumentElement.SelectNodes("Employee");

foreach (XmlNode emp in nodeList)
{
    foreach (XmlNode child in emp.ChildNodes)
    {
        Response.Write(child.LocalName);
        Response.Write(":");
        Response.Write(child.InnerText);
        Response.Write("\n");
    }

}

希望有所帮助。如果它确实将其标记为答案。 -Milind

答案 3 :(得分:0)

我相信你做得对。如果您查看aspx页面的源代码,您应该看到XML标记。

<employee_info><employee><name>Blah<br></name><id>001<br></id><dept>ISDC<br></dept></employee><employee><name>Bleh<br></name><id>002<br></id><dept>COE<br></dept></employee><employee><name>Bah<br></name><id>003<br></id><dept>Roll_Out<br></dept></employee></employee_info>