<Tasks>
<AuxFiles>
<FileType AttachmentType='csv' FileFormat ='*.csv'>
</AuxFiles>
</Tasks>
如果我知道AttachmentType
,那麼C#中的語法是什麼FileFormat
?使用C#讀取XML
任何和所有的幫助總是讚賞。
<Tasks>
<AuxFiles>
<FileType AttachmentType='csv' FileFormat ='*.csv'>
</AuxFiles>
</Tasks>
如果我知道AttachmentType
,那麼C#中的語法是什麼FileFormat
?使用C#讀取XML
任何和所有的幫助總是讚賞。
試試這個代碼:
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;
}
}
您可以使用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);
Jon Skeet的解決方案比這個更強大,因爲如果沒有類型匹配或者元素沒有FileFormat屬性,它不會導致'NullReferenceException'。但這個想法是一樣的。 – carlosfigueira
我會使用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();
這會給null
如果沒有匹配的元素,或者如果第一FileType
具有匹配AttachmentType
沒有FileFormat
屬性。
您可以使用XPATH查詢XML文件中的任何元素。
看到這個ULR:http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm
檢查也是這個SO帖子: 「如何查詢同行的XMLNode .NET」
做起來的另一種方式:
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;
是你的問題:鑑於這個XML文件,我想找到Fileformat屬性值爲給定的AttachtmentType?所以當你尋找「csv」時你想找到「* .csv」? – Eddy