.net 在C#中验证后无法从XmlReader检索属性名称/值

v8wbuo2f  于 12个月前  发布在  .NET
关注(0)|答案(1)|浏览(108)

我需要写一个c#代码,当验证失败时,从XML中提取属性信息。下面的代码能够给予我验证失败的确切属性,但我还需要来自父节点中存在的属性的其他信息。
XML:

<Payload xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlVersion="1.0" createDate="2023-11-07T14:23:08" messageType="TEST">
    <Orders>
        <OrderHeader resultsIndicator="F" orderNumber="2000100" orderStatus="FIN" latestShipDate="4/23/2023 12:00:00 AM" cusNumber="791053" cusName="Apple, Ms.Rose" deliveryTerms="HOME" paymentType="AMEX" Destination="TX">
            <OrderDetail resultsIndicator="F" lot="1234" sequence="01" invoice="FGD123401" finalDestination="75013" resultsMessage="DELIVERED" brandNumber="100141" brandName="LG">
<OrderCostingDetail expenseCode="ADMIN" expenseCategory="ADM" rate="2499.50" indicator="F" qualifier="SALE" unitCost="2499.50" level="002"/>
                <OrderCostingDetail expenseCode="ADMIN" expenseCategory="ADM" rate="125.00" indicator="F" qualifier="SALE" unitCost="" level="002"/>
                <OrderCostingDetail expenseCode="ADMIN" expenseCategory="ADM" rate="5879.20" indicator="F" qualifier="SALE" unitCost="5879.20" level="002"/>
            </OrderDetail>
        </OrderHeader>
        <OrderHeader resultsIndicator="I" orderNumber="2000101" orderStatus="INIT" latestShipDate="12/10/2023 12:00:00 AM" cusNumber="56782" cusName="Roy, Mr.Ralph" deliveryTerms="HOME" paymentType="VISA" Destination="TX">
            <OrderDetail resultsIndicator="I" lot="1234" sequence="01" invoice="FGD123401" finalDestination="75013" resultsMessage="DELIVERED" brandNumber="100141" brandName="LG">
                <OrderCostingDetail expenseCode="ADMIN" expenseCategory="ADM" rate="24.00" indicator="I" qualifier="SALE" unitCost="24.00" level="004"/>
            </OrderDetail>
        </OrderHeader>
    </Orders>
</Payload>

字符串
代码:

private static void PerformValidation(XmlTextReader xmlTextReader, XmlSchemaSet schemas)
{
    if (schemas == null)
    {
        throw new ArgumentNullException("schemas");
    }

    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas = schemas;
    settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; //sarul1
    // settings.ValidationEventHandler += (sender, args) => error = ValidationCallback(sender, args);

    string chkatt = string.Empty;

    using (XmlReader reader = XmlReader.Create(xmlTextReader, settings))
    {
        try
        {
            do
            {
                chkatt = string.Concat("orderNo.: ",reader.GetAttribute("orderNumber"), ", Lot:", reader.GetAttribute("lot"), ", Seq:", reader.GetAttribute("sequence"));
            } while (reader.Read());
        }
        catch(Exception ex)
        {
            string error = ex.Message.ToString() + chkatt;
        }
        finally
        {
            reader.Close();   
        }
    }
}


我在main函数中调用上面的方法,根据预定义的模式验证是否有任何NULL字段。
“unitCost”属性无效...字符串“"不是有效的Decompression值
我需要添加其他属性信息,如orderNumber,Lot和Sequence到此消息(在本例中:orderNumber = 2000100,Lot = 1234,Seq = 01),我无法使用此代码。
请帮助我前进!

1wnzp6jl

1wnzp6jl1#

PerformValidation函数在错误消息中缺少上下文,因为它没有跟踪父节点中的属性值。
考虑这个更新的代码:

private static void PerformValidation(XmlTextReader xmlTextReader, XmlSchemaSet schemas)

字符串
{ if(schemas == null){ throw new ArgumentNullException(“schemas”); }

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = schemas;
settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;

string orderNumber = string.Empty;
string lot = string.Empty;
string sequence = string.Empty;

using (XmlReader reader = XmlReader.Create(xmlTextReader, settings))
{
    try
    {
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
                if (reader.Name == "OrderHeader")
                {
                    orderNumber = reader.GetAttribute("orderNumber");
                }
                else if (reader.Name == "OrderDetail")
                {
                    lot = reader.GetAttribute("lot");
                    sequence = reader.GetAttribute("sequence");
                }
            }
            else if (reader.NodeType == XmlNodeType.Attribute && reader.Value == string.Empty)
            {
                string errorMessage = $"Validation error in OrderNo.: {orderNumber}, Lot: {lot}, Seq: {sequence}. ";
                
                // Handle or log the error message as needed
                Console.WriteLine(errorMessage);
            }
        }
    }
    catch (Exception ex)
    {
        string error = ex.Message.ToString();
        // Handle or log the exception as needed
        Console.WriteLine(error);
    }
    finally
    {
        reader.Close();
    }
}


}
这段代码引入了变量(orderNumber、lot和sequence)来存储这些值,从而在发生验证错误时提供更多信息性的错误消息。
给予它一个尝试,让我知道如果需要进一步的修改.和请不要忘记标记为答案,如果这个答案已经解决了你的问题.:)

相关问题