简体   繁体   English

从XML节点读取特定值

[英]Read specific value from XML node

I have a XML file and I need to read a value of a particular node in the XML file. 我有一个XML文件,我需要读取XML文件中特定节点的值。

Code: 码:

public static string GetElementByName(string responseContent,string attributeName, string attributeValue)
    {
        string result = "";
        XmlTextReader textReader = new XmlTextReader(new System.IO.StringReader(responseContent));

        while (textReader.Read())
        {
            switch (textReader.NodeType)
            {
                case XmlNodeType.Element:
                    if (!textReader.IsEmptyElement)
                    {
                        if (textReader.GetAttribute(attributeName) == attributeValue)
                        {
                            result = textReader.ReadInnerXml();
                        }
                    }
                    break;
                case XmlNodeType.Text:
                    break;
                case XmlNodeType.XmlDeclaration:
                case XmlNodeType.ProcessingInstruction:
                    break;
                case XmlNodeType.Comment:
                    break;
                case XmlNodeType.EndElement:
                    break;
            }
        }
        return result;
    }

Here, I pass the xml content as a string (responseContent), the attribute name and the attribute value to get the actual value of that particular node. 在这里,我将xml内容作为字符串(responseContent),属性名称和属性值传递,以获取该特定节点的实际值。 This works if the xml node is like 如果xml节点像

<Reference ReferenceType="ABC" AssignedBy="Buyer">123</Reference>
<Reference ReferenceType="DEF" AssignedBy="Buyer">456</Reference>

var value1 = GetElementByName(xmlContent,"ReferenceType","ABC"); // value1 = 123

var value2 = GetElementByName(xmlContent,"ReferenceType","DEF"); // value2 = 456

But Now a new scenario is to be covered. 但是现在要涵盖一个新的场景。

I have a xml like 我有一个像

<Component>
    <Classification ClassificationType="BOOK">
          <SubClassification SubClassificationType="FICTION"/>
    </Classification>
    <Reference ReferenceType="ABC">123</Reference>
</Component>
<Component>
    <Classification ClassificationType="MOVIES">
          <SubClassification SubClassificationType="ROMANCE"/>
    </Classification>
    <Reference ReferenceType="ABC">456</Reference>
</Component>

Now, I need to call a function, one should return the value 123 of BOOK classification and other should return the value of 456 of MOVIES classification. 现在,我需要调用一个函数,一个应返回BOOK分类的值123,另一个应返回MOVIES分类的456的值。

How to check nodes and then extract the value. 如何检查节点,然后提取值。

Update #1: 更新#1:

Lets say If 可以说如果

I call GetElement(xmlContent, "BOOK", "ReferenceType", "ABC"), then I should get 123. 我叫GetElement(xmlContent,“ BOOK”,“ ReferenceType”,“ ABC”),那么我应该得到123。

I call GetElement(xmlContent, "MOVIES", "ReferenceType", "ABC"), then I should get 456. 我叫GetElement(xmlContent,“ MOVIES”,“ ReferenceType”,“ ABC”),那么我应该得到456。

Nice Way to do it, 做这件事的好方法

First, convert your XML in c# Models 首先,在c#模型中转换XML

Here is how your C# Model class Generated using xmltocsharp 这是使用xmltocsharp生成 C#模型类的方式

[XmlRoot(ElementName = "SubClassification")]
public class SubClassification
{
    [XmlAttribute(AttributeName = "SubClassificationType")]
    public string SubClassificationType { get; set; }
}

[XmlRoot(ElementName = "Classification")]
public class Classification
{
    [XmlElement(ElementName = "SubClassification")]
    public SubClassification SubClassification { get; set; }
    [XmlAttribute(AttributeName = "ClassificationType")]
    public string ClassificationType { get; set; }
}

[XmlRoot(ElementName = "Reference")]
public class Reference
{
    [XmlAttribute(AttributeName = "ReferenceType")]
    public string ReferenceType { get; set; }
    [XmlText]
    public string Text { get; set; }
}

[XmlRoot(ElementName = "Component")]
public class Component
{
    [XmlElement(ElementName = "Classification")]
    public Classification Classification { get; set; }
    [XmlElement(ElementName = "Reference")]
    public Reference Reference { get; set; }
}

[XmlRoot(ElementName = "Root")]
public class Root
{
    [XmlElement(ElementName = "Component")]
    public List<Component> Component { get; set; }
}

Then here is a helper method that will do the trick 然后这是一个可以解决问题的辅助方法

public static string GetValue(string data, string classificationTypeValue, string referenceTypeValue)
{
    // Serializing XML here
    Root root;
    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(Root));

    using (StringReader sr = new StringReader(data))
    {
        root = (Root)ser.Deserialize(sr);
    }

    if (root != null)
    {
        // First we'll get a components which have given classificationType E.g (Books,Movies)
        List<Component> componentWithReferenceType = root.Component.Where(x => x.Classification.ClassificationType == classificationTypeValue).ToList();
        // Now once we have componets with given classificationType all we have to do is grab it's first child and return it's referenceText
        return componentWithReferenceType.First(x => x.Reference.ReferenceType == referenceTypeValue).Reference.Text;
    }

    return string.Empty;
}

You need to read sibling of Classification inside Component by using ReadToNextSibling() function like. 您需要使用ReadToNextSibling()函数读取Component内部的Classification同级项。

public static string GetElementByName(string responseContent, string classification, string attributeName, string attributeValue)
{
    string result = "";
    XmlTextReader textReader = new XmlTextReader(new System.IO.StringReader(responseContent));

    while (textReader.Read())
    {
        switch (textReader.NodeType)
        {
            case XmlNodeType.Element:
                if (!textReader.IsEmptyElement)
                {
                    if (textReader.Name == "Classification" && textReader.GetAttribute("ClassificationType") == classification)
                    {
                        textReader.ReadToNextSibling("Reference");

                        if (textReader.GetAttribute(attributeName) == attributeValue)
                        {
                            result = textReader.ReadInnerXml();
                        }
                    }

                }
                break;
            case XmlNodeType.Text:
                break;
            case XmlNodeType.XmlDeclaration:
            case XmlNodeType.ProcessingInstruction:
                break;
            case XmlNodeType.Comment:
                break;
            case XmlNodeType.EndElement:
                break;
        }
    }
    return result;
}

Output: 输出:

在此处输入图片说明

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM