Đây là một chức năng mà tôi sử dụng là hoạt động hoàn hảo để phân tích các tệp xml. tôi đã bao gồm một lớp 'delimeter' mà bạn có thể sử dụng để lưu trữ delimeters xml như
<startTag></endTag>
Thật dễ dàng để sử dụng, và hoạt động như một nét duyên dáng ... cho tôi biết nếu bạn có bất kỳ câu hỏi
sử dụng các chức năng như thế này:
XmlDataManager.List<XmlManager.Delimeter> delimeters = new List<XmlManager.Delimeter>("<result>","</result>");
int[] splitIndexArray = { 1 }; // Tells the function where to split in case where the same value occurs multiple times in a line... usually 1 need an entry for each value
String testValue = "";
List<String> values = new List<String> {testValue}
XmlDataManager.ReadValues(delimeters, values, `<xmlFileNameHere>,` splitIndexArray);
đây là lớp:
public class XmlDataManager
{
const String XML_FILE_WRITE_FAIL = "Could not write to xml file";
const String XML_FILE_READ_FAIL = "Could not read from xml file";
const String XML_FILE_WRITE_BUILDER_FAIL = "Could not write values to string";
/// <summary>
///
/// </summary>
public struct Delimeter
{
internal String StartDelimeter { get { return _startDelimeter; } }
internal String EndDelimeter { get { return _endDelimeter; } }
private readonly String _startDelimeter;
private readonly String _endDelimeter;
public Delimeter(String startDelimeter, String endDelimeter)
{
_startDelimeter = startDelimeter;
_endDelimeter = endDelimeter;
}
public Delimeter(String startDelimeter)
{
_startDelimeter = startDelimeter;
_endDelimeter = String.Empty;
}
}
public static void ReadValuesLineByLine( List<Delimeter> elementDelimeters,
List<String> values,
String fileName,
int[] splitIndexes)
{
try
{
using (StreamReader sr = new StreamReader(fileName))
{
String line = sr.ReadLine();
while (!sr.EndOfStream)
{
for (int i = 0; i <= values.Count-1; i++)
{
if (line.Contains(elementDelimeters[i].StartDelimeter))
{
String[] delimeters = { elementDelimeters[i].StartDelimeter, elementDelimeters[i].EndDelimeter };
String[] elements = line.Split(delimeters, StringSplitOptions.None);
values[i] = elements[splitIndexes[i]];
}
}
line = sr.ReadLine();
}
}
}
catch(Exception ex)
{
throw new Exception(XML_FILE_READ_FAIL, ex);
}
}
}
Peter
Gợi ý: Nút gốc của bạn được đặt tên là 'whmcsapi' –
có thể trùng lặp của [Làm cách nào để đọc và phân tích cú pháp tệp XML trong C#?] (Http://stackoverflow.com/questions/642293/how-do- i-read-and-parse-an-xml-file-in-c) –
Vấn đề là tôi không phân tích cú pháp một tệp, tôi có dữ liệu XML trong một chuỗi. Tất cả mọi thứ tôi tìm thấy là làm thế nào để phân tích một tập tin. –