linq在子节点中分隔xml值

时间:2016-06-08 10:13:53

标签: c# xml linq

我想创建一个配置文件来验证用户输入。我如何访问不同的节点 - 值似乎是元素内的每个节点。我想获取单独的值来检查输入的长度和正确的格式等。

C#

var xml = XElement.Load (@"C:\Project\conf\config.xml");

foreach(var child in xml
                    .Element("Felder").Elements())
{
    string cld = child.Name + " " + child.Value;
}

的xml:

<?xml version="1.0"?>
<Config>
    <Anrede>
        <key_1>Testval</key_1>
    </Anrede>
    <Felder>
        <KNR>
            <Length>6</Length>
            <Format>######</Format>
        </KNR>
        <AddressStatus>
            <Length>1</Length>
            <Format>0</Format>
        </AddressStatus>
        <adressResearch>
            <Length>1</Length>
            <Format>0</Format>
        </adressResearch>
        <AnredeNr>
            <Length>1</Length>
            <Format>0</Format>
        </AnredeNr>
    </Felder>
</Config>

输出:

KNR 6######
AddressStatus 10
adressResearch 10
AnredeNr 10

期望的输出: KNR [6,######]甚至更好KNR.Length = 6,KNR.Format =&#34; ######&#34;

有没有更好的方法来编写这样的配置?

3 个答案:

答案 0 :(得分:3)

此linq查询(查询语法中为SelectMany

IEnumerable<DictionaryEntry> keyValuePairs = 
                from child in xml.Element("Felder").Elements()
                from tag in child.Elements()
                select new DictionaryEntry(String.Format("{0}.{1}", child.Name, tag.Name), tag.Value);

给出当前xml结构的输出(格式可能不同):

{ Key = KNR.Length, Value = 6 }
{ Key = KNR.Format, Value = ###### }
{ Key = AddressStatus.Length, Value = 1 }
{ Key = AddressStatus.Format, Value = 0 }
{ Key = adressResearch.Length, Value = 1 }
{ Key = adressResearch.Format, Value = 0 }
{ Key = AnredeNr.Length, Value = 1 }
{ Key = AnredeNr.Format, Value = 0 }

使用fiddle

进行尝试

答案 1 :(得分:0)

Value将返回所有后代文本节点,因此当您获得Value时,例如KNR它会返回6######

您需要单独访问子元素值:

foreach(var field in xml.Element("Felder").Elements())
{
    var fieldName = field.Name.LocalName;
    var length = (int)field.Element("Length");
    var format = (string)field.Element("Format");

    // do what you want with these
    // or ...

    var childValues = field.Elements().Select(x => x.Value);
    var childValuesCommaSeparated = string.Join(","  childValues);        
}

答案 2 :(得分:0)

如果要搜索特定节点的Xml数据以获取其子节点,可以使用Linq to XML。例如:

Length Format
6      ###### 

结果:

var result1 = xdoc.Descendants("Felder").Elements()
                .Select(x=>new
                    {
                        Name = x.Name,
                        Length = x.Element("Length").Value,
                        Format = x.Element("Format").Value
                    })
                .ToList();
foreach(var setting in result1)
{
    Console.WriteLine("{0} | {1} | {2}", 
                 setting.Name, setting.Length, setting.Format);
}

如果您希望让每个节点都获得设置的名称,长度和格式列表,您可以尝试这样做:

OkHttpClient client = ...;

OkHttpClient.Builder b = client.newBuilder();
b.networkInterceptors().removeIf(MyInterceptor.class::isInstance);
client2 = b.build();