簡體   English   中英

使用C#從xml文件讀取動態元素

[英]Reading dynamic elements from the xml file using c#`

我想從xml文件中動態讀取xml元素(我的意思是不對元素名稱進行硬編碼)。 我無法使用XmlReader.ReadToDescendant方法,因為它期望本地名稱(在我的情況下會有所不同)。 例如,在這種情況下,我需要閱讀元素A,B,C,D等。

<?xml version="1.0" encoding="UTF-8"?>
<test Version="2010" xmlns="http://test.org/2010/values">
<A>
    <Data>
     <Somedata></Somedata>
    </Data>
    <Rows>
      <Row></Row>
      <Row></Row>
    </Rows>
</A>
<B>
    <Data>
     <Somedata></Somedata>
    </Data>
    <Rows>
      <Row></Row>
      <Row></Row>
    </Rows>
</B>
<C>
    <Data>
     <Somedata></Somedata>
    </Data>
    <Rows>
      <Row></Row>
      <Row></Row>
    </Rows>
</C>
<D>
    <Data>
     <Somedata></Somedata>
    </Data>
    <Rows>
      <Row></Row>
      <Row></Row>
    </Rows>
</D>
</test>

請幫我。

那很簡單:

XDocument doc = XDocument.Load("test.xml");
string name = GetNameFromWherever();
foreach (XElement match in doc.Descendants(name))
{
    ...
}

這是使用LINQ to XML -一個可愛的API為XML如果你使用.NET 3.5或更高版本......這比使用好得多 XmlReader

為了將XML內容動態生成為另一組類,您可以執行以下操作:

class GenericNode
{
  private List<GenericNode> _Nodes = new List<GenericNode>();
  private List<GenericKeyValue> _Attributes = new List<GenericKeyValue>();
  public GenericNode(XElement Element)
  {
     this.Name = Element.Name;
     this._Nodes.AddRange(Element.Elements()
                                 .Select(e => New GenericNode(e));
     this._Attributes.AddRange(
                Element.Attributes()
                       .Select(a => New GenericKeyValue(a.Key, a.Value))
  }

  public string Name { get; private set; }
  public IEnumerable<GenericNode> Nodes
  {
    get
    {
       return this._Nodes;
    }       
  }
  public IEnumerable<GenericKeyValue> Attributes
  {
    get
    {
       return this._Attributes;
    }
  }
}

class GenericKeyValue
{
  public GenericKeyValue(string Key, string Value)
  {
     this.Key = Key;
     this.Value = Value;
  }
  public string Key { get; set; }
  public string Value { get; set; }
}

然后,您只需:

XElement rootElement = XElement.Parse(StringOfXml); // or
XElement rootElement = XElement.Load(FileOfXml);

GenericNode rootNode = new GenericRode(rootElement);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM