读取不带xsd文件的带有架构的XML

本文关键字:XML 文件 xsd 读取 | 更新日期: 2023-09-27 18:24:20

本周我收到了一个复杂的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?

读取不带xsd文件的带有架构的XML

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

读取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();
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);