<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