2

早晨,

我有一些正在返回的 XML,我需要读取每个结果节点,然后将它们放入我的数据库中。

所以 SKU,ResultMessageCode 将被存储。如果 ResultCode 被标记为错误,我只需要拉出这些。

 <Message>
    <MessageID>1</MessageID>
    <ProcessingReport>
        <DocumentTransactionID>123456789</DocumentTransactionID>
        <StatusCode>Complete</StatusCode>
        <ProcessingSummary>
            <MessagesProcessed>2</MessagesProcessed>
            <MessagesSuccessful>0</MessagesSuccessful>
            <MessagesWithError>2</MessagesWithError>
            <MessagesWithWarning>0</MessagesWithWarning>
        </ProcessingSummary>
        <Result>
            <MessageID>1</MessageID>
            <ResultCode>Error</ResultCode>
            <ResultMessageCode>90205</ResultMessageCode>
            <ResultDescription>Some Text Here</ResultDescription>
            <AdditionalInfo>
                <SKU>12345</SKU>
            </AdditionalInfo>
        </Result>
        <Result>
            <MessageID>2</MessageID>
            <ResultCode>Error</ResultCode>
            <ResultMessageCode>90205</ResultMessageCode>
            <ResultDescription>Some Text Here</ResultDescription>
            <AdditionalInfo>
                <SKU>67890</SKU>
            </AdditionalInfo>
        </Result>
    </ProcessingReport>
</Message>

我在 Stackoverflow 的其他地方找到了这个,并认为这可能是我所追求的。

 foreach (XmlNode chldNode in node.ChildNodes)
    {
            **//Read the attribute Name**
        if (chldNode.Name == Employee)
        {                    
            if (chldNode.HasChildNodes)
            {
                foreach (XmlNode item in node.ChildNodes)
                { 

                }
            }
        }
    }

我在这里假设是否正确,并且需要使用类似的东西?但是,上述示例中的 XML 略小。

提前致谢。

4

6 回答 6

2

试试LINQ-XML

XDocument doc = XDocument.Parse(xmlStr);

var results = doc.Root.Descendants("Result")
                    .Where(p => p.Element("ResultCode").Value == "Error");
foreach (var t in results)
 {
  var resultCode = t.Element("ResultMessageCode").Value;
  var sku = t.Element("AdditionalInfo").Element("SKU").Value;
  //
 }
于 2012-07-10T09:00:47.780 回答
1

另一种(简洁的)方法是使用 XPath 和 Linq:

var dom = new XmlDocument();
dom.LoadXml(xml);
var results = dom.SelectNodes("//Message/ProcessingReport/Result[ResultCode/text() = 'Error']")
                .Cast<XmlNode>()
                .Select(n => new { 
                    ResultMessageCode = n.SelectSingleNode("ResultMessageCode/text()"), 
                    SKU = n.SelectSingleNode("AdditionalInfo/SKU/text()")
                });
于 2015-07-15T19:43:53.313 回答
0

是的,您需要使用类似的东西或使用LINQ to XML,它可以为您提供更干净和紧凑的代码:

using System;
using System.Linq;
using System.Xml.Linq;

class Program
{
    private const string Xml =
        @"<Message>
    <MessageID>1</MessageID>
    <ProcessingReport>
        <DocumentTransactionID>123456789</DocumentTransactionID>
        <StatusCode>Complete</StatusCode>
        <ProcessingSummary>
            <MessagesProcessed>2</MessagesProcessed>
            <MessagesSuccessful>0</MessagesSuccessful>
            <MessagesWithError>2</MessagesWithError>
            <MessagesWithWarning>0</MessagesWithWarning>
        </ProcessingSummary>
        <Result>
            <MessageID>1</MessageID>
            <ResultCode>Error</ResultCode>
            <ResultMessageCode>90205</ResultMessageCode>
            <ResultDescription>Some Text Here</ResultDescription>
            <AdditionalInfo>
                <SKU>12345</SKU>
            </AdditionalInfo>
        </Result>
        <Result>
            <MessageID>2</MessageID>
            <ResultCode>Error</ResultCode>
            <ResultMessageCode>90205</ResultMessageCode>
            <ResultDescription>Some Text Here</ResultDescription>
            <AdditionalInfo>
                <SKU>67890</SKU>
            </AdditionalInfo>
        </Result>
    </ProcessingReport>
</Message>
";

    static void Main(string[] args)
    {
        var doc = XDocument.Parse(Xml);

        foreach (var result in doc.Descendants("Result").Where(x => x.Element("ResultCode").Value == "Error"))
        {
            Console.WriteLine("MessageID: {0}; ResultMessageCode: {1}; ResultDescription: {2}", 
                result.Element("MessageID").Value,
                result.Element("ResultMessageCode").Value,
                result.Element("ResultDescription").Value
                );
        }
    }
}
于 2012-07-10T08:48:55.127 回答
0
using (XmlReader xmlr = XmlReader.Create(@"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"))
        {
            xmlr.ReadToFollowing("Cube");
            while (xmlr.Read())
            {
                if (xmlr.NodeType != XmlNodeType.Element) continue;

这样您就可以导航到您只需要的节点。这只是一种方法。Linq to XML 是另一种方式,但比上面的代码段更占用资源。

于 2012-07-10T08:48:55.940 回答
0

您可以为您的 XML 结构创建一组类,并为这些类添加可序列化的键,

[Serializable()]
public class Message
{
    public int MessageId {get; set;}

    private ProcessingReport processingReport = new ProcessingReport();
    ...
}

然后使用 XmlSerializer 将您的 XML 解析为类

    XmlSerializer SerializerObj = new XmlSerializer(typeof(Message));

    // Open your XML file (or use a reader if it's a a location)
    FileStream ReadFileStream = new FileStream(@"C:\test.xml", FileMode.Open, FileAccess.Read, FileShare.Read);

    Message message = (Message)SerializerObj.Deserialize(ReadFileStream);

    ReadFileStream.Close();
于 2012-07-10T09:00:38.467 回答
0

可以使用xpath找到“ResultCode”节点,然后判断是否出错。

http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectnodes%28v=vs.71%29.aspx http://support.microsoft.com/kb/307548

using System.Xml;

XmlDocument doc = new XmlDocument();
doc.LoadXml(XML_String);

XmlNode result = doc.DocumentElement.SelectSingleNode("//ResultCode");

if (result == null)
    throw new Exception("Error")

if (result.Value == "Error")
    //Message is in Error.
else
    //Message is OK.
于 2012-07-10T11:22:52.723 回答