簡體   English   中英

使用 C# 讀取 XML

[英]Reading XML using C#

<Tasks>
    <AuxFiles>
        <FileType AttachmentType='csv' FileFormat ='*.csv'>
    </AuxFiles>
</Tasks>

如果我知道AttachmentType , C# 獲取FileFormat的語法是什么?

任何和所有的幫助總是值得贊賞的。

我會使用 LINQ 到 XML:

var doc = XDocument.Load("file.xml");

var format = doc.Descendants("FileType")
                .Where(x => (string) x.Attribute("AttachmentType") == type)
                .Select(x => (string) x.Attribute("FileFormat"))
                .FirstOrDefault();

如果沒有匹配的元素或者具有匹配AttachmentType的第一個FileType沒有FileFormat屬性,這將給出null

您可以使用XElement和查詢支持。

        XElement element = XElement.Parse(@"<Tasks>
  <AuxFiles>
    <FileType AttachmentType='csv' FileFormat ='*.csv' />
  </AuxFiles>
</Tasks>");
        string format = element.Descendants("FileType")
            .Where(x => x.Attribute("AttachmentType").Value == "csv")
            .Select(x => x.Attribute("FileFormat").Value)
            .First();

        Console.WriteLine(format);

試試這個代碼:

string fileFormat = string.Empty;


XmlDocument xDoc = new XmlDocument();
xDoc.Load(fileName);

XmlNodeList auxFilesList = xDoc.GetElementsByTagName("AuxFiles");
for (int i = 0; i < auxFilesList.Count; i++)
{
   XmlNode item = classList.Item(i);
   if (item.Attributes["AttachmentType"].Value == "csv")
   {
      fileFormat = item.Attributes["FileFormat"].Value;
   }
}

另一種方法是:

XmlDocument xDoc = new XmlDocument();
xDoc.Load("path\\to\\file.xml");

// Select the node where AttachmentType='csv'
XmlNode node = xDoc.SelectSingleNode("/Tasks/AuxFiles/FileType[@AttachmentType='csv']");
// Read the value of the Attribute 'FileFormat'
var fileFormat = node.Attributes["FileFormat"].Value;

您可以使用 XPATH 查詢 XML 文件中的任何元素。

看到這個 ULR: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm

還要檢查這個 SO 帖子:“如何查詢對等 XMLNode .NET”

暫無
暫無

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

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