使用没有xsd文件的模式读取XML

时间:2013-07-22 15:09:32

标签: c# xml xml-serialization xmlreader xmlnodelist

本周我收到了一个复杂的XML文件,它是基于模式的,但我没有收到任何xsd文件,我需要读取这个文件的每个节点。

XML示例:

<xc:XmlTest xmlns:xc="XmlTest" xmlns:mp="bs.TestParameters" xmlns:rt="bs.TestParameters.Parameter1" xmlns:rtcu="bs.TestParameters.Parameter1.Var">
<xc:XmlTestArea xc:value="TestParameters">
    <mp:Name xc:Value="raddesso" xmlns:mp="bs.TestParameters">
        <mp:Date xc:Value="20130215">
            <rt:RunTest xmlns:rt="bs.TestParameters.Parameter1">
                <rtcu:Var xmlns:rtcu="bs.TestParameters.Parameter1.Var">
                    <mp:FinalValue>1234</mp:FinalValue>
                </rtcu:Var>
            </rt:RunTest>
        </mp:Date>
        <mp:Date xc:Value="20130216">
            <rt:RunTest xmlns:rt="bs.TestParameters.Parameter1">
                <rtcu:Var xmlns:rtcu="bs.TestParameters.Parameter1.Var">
                    <mp:FinalValue>23234</mp:FinalValue>
                </rtcu:Var>
            </rt:RunTest>
        </mp:Date>
    </mp:Name>
</xc:XmlTestArea>
</xc:XmlTest>

这只是使用虚假数据的真实文件的一个示例。

有没有办法在这个节点上做foreach从每个日期找到FinalValue?

2 个答案:

答案 0 :(得分:5)

您不需要架构来读取文件。模式仅用于验证文件(以检查完整性)。但这一步是可选的。

读取XML文件。我建议使用Linq-to-XML。

const string mpNamespace = "bs.TestParameters";

XDocument xDocument = XDocument.Load("C:/Path to the file.xml");

List<string> finalValues = (from dateNode in xDocument.Descendants(XName.Get("Date", mpNamespace))  // Gets all Date nodes in the document
                            from finalValueNode in dateNode.Descendants(XName.Get("FinalValue", mpNamespace))  // Gets all FinalValue nodes in the Date nodes
                            select finalValueNode.Value  // Gets the value of each FinalValue node
                           ).ToList();

更新

要返回DateFinalValue,您可以使用匿名类型:

const string mpNamespace = "bs.TestParameters";
const string xcNamespace = "XmlTest";

XDocument xDocument = XDocument.Load("C:/Path to the file.xml");

var finalValues = (from dateNode in xDocument.Descendants(XName.Get("Date", mpNamespace))  // Gets all Date nodes in the document
                   from finalValueNode in dateNode.Descendants(XName.Get("FinalValue", mpNamespace))  // Gets all FinalValue nodes in the Date nodes
                   select new  // Creates an instance of an anonymous type with Date and FinalValue
                   {
                       Date = dateNode.Attribute(XName.Get("Value", xcNamespace)).Value,
                       FinalValue = finalValueNode.Value  // Gets the value of each FinalValue node
                   }
                  ).ToList();

答案 1 :(得分:0)

XmlDocument doc = new XmlDocument();
doc.Load("path to xml file");

XmlNodeList finalValues = doc.GetElementByTagName("FinalValue");

finalValues将是一个标签名为“FinalValue”的节点列表,然后您可以在列表中读取内部文本和故事。

List<string> values = new List<string>();
foreach(XmlNode node in finalValues)
    values.Add(node.InnerText);
相关问题