获取不同XML的特定元素

时间:2018-06-08 09:41:01

标签: c# xml string

我需要从xml string获取一个特定元素才能知道其相应的concrete typedeserialize。让我们调用Function Code作为特定元素,获取此元素对我来说有点挑战。

每个function code对应于特定的架构设计,它看起来像这样:

1    <?xml version="1.0" encoding="utf-8"?>
2    <Document xmlns="some.namespace.of.schema.design.1">
3      <SchemaDesign1>
4        <Header>
5          <FunctionCode>FunctionCode1</FunctionCode>
6          <OtherElement1>...</OtherElement1>
7          <OtherElement2>...</OtherElement2>

我需要line 5上{1}}的功能代码元素的值。但请注意,在FunctionCode1上,元素名称也特定于其line 3

因此对于另一个功能代码,例如concrete typeFunctionCode2上的元素将不相同:

line 3

我只能考虑使用1 <?xml version="1.0" encoding="utf-8"?> 2 <Document xmlns="some.namespace.of.schema.design.2"> 3 <SchemaDesign2> 4 <Header> 5 <FunctionCode>FunctionCode2</FunctionCode> 6 <OtherElement1>...</OtherElement1> 7 <OtherElement2>...</OtherElement2> 并获取string.IndexOf("<FunctionCode>")的值,直到找到相应的结束标记。如果没有阅读整个字符串,有没有更好的方法呢?

以下是我得到的示例function code

XML

1 个答案:

答案 0 :(得分:1)

因此,对于每个示例XML,您有两个XDocument,分别称为doc1doc2,然后此代码:

var ns1 = doc1.Root.GetDefaultNamespace();
var ns2 = doc2.Root.GetDefaultNamespace();

var functionCode1 = doc1.Root.Descendants(ns1 + "FunctionCode").First().Value;
var functionCode2 = doc2.Root.Descendants(ns2 + "FunctionCode").First().Value;

Console.WriteLine(functionCode1);
Console.WriteLine(functionCode2);

...生产:

FunctionCode1
FunctionCode2

因此,鉴于您有这种格式的未知XML文档,一般情况是:

var ns = doc.Root.GetDefaultNamespace();

var functionCode = doc.Root.Descendants(ns + "FunctionCode").First().Value;
相关问题