0

我的 xml 如下所示

<Employee>
      <Emp>
        <Name id="1" link="/office1/manager"></Name>
        <Name id="2" link="/office/sweeper"></Name>
        <Name id="3" link="/office2/manager"></Name>
       </Emp>
  </Employee>

我想获取在“链接”中包含字符串“manager”的员工的“id”

4

3 回答 3

1
var xDoc = XDocument.Parse(xml); //XDocument.Load(filename)
var ids = xDoc.Descendants("Name")
            .Where(n => n.Attribute("link").Value.Contains("/manager"))
            .Select(n => n.Attribute("id").Value)
            .ToList();
于 2012-10-31T10:34:05.923 回答
1

使用 linq 到 xml:

XDocument doc = XDocument.Load("XMLFilePath");
var selectors = from elements in doc.Elements("Employee").Elements("Emp").Elements("Name")
                where elements.Attribute("link").Value.Contains("manager")
                select elements;

string ids = string.Empty;
foreach (var element in selectors)
{
        ids  += element.Attribute("id").Value + ",";
}

此外,对于从字符串加载,您可以使用:

XDocument doc = XDocument.Parse(xmlString);
于 2012-10-31T10:36:13.790 回答
0
    //SELECT THE VALUES FROM XML USING C#

            <?xml version="1.0" encoding="iso-8859-1"?>
            <CONFIG>
              <UsersList>
                <SystemName>DOTNET-PC</SystemName>
                <UserName>KARTHIKEYAN</UserName>
                <ImagePath>C:\Users\DEVELOPER\AppData\Roaming\Office Messenger\assets\insta.jpg</ImagePath>
                <PhotoPath>C:\Users\DEVELOPER\AppData\Roaming\Office Messenger\assets\NoPhoto.png</PhotoPath>
                <UserStatus>Available</UserStatus>
                <CustomStatus>Available</CustomStatus>
                <theme>FF8B0000</theme>
              </UsersList>
            </CONFIG>                       //XML DOCUMENT

        //C#

DataSet ds = new DataSet();
try
{
   ds.ReadXml("C:\\config.xml");
}
catch { };

if (ds.Tables.Count > 0)
{
  var results = from myRow in ds.Tables[0].AsEnumerable() where myRow.Field<string>    ("SystemName") == SystemInformation.ComputerName select myRow;//ds.Tables[0] is <CONFIG> tag //in where SystemName=My system name to select the values from xml
  foreach (var cust in results)
  {
    string _myName = cust["UserName"].ToString();
    string _myLogoPath = cust["ImagePath"].ToString();
    string _customStatus = cust["CustomStatus"].ToString();
    string _myPhotoPath = cust["PhotoPath"].ToString();
  }
}


//CREATE XML FROM C#

XDocument xmlDoc = XDocument.Load("C:\\config.xml");
xmlDoc.Root.Add(new XElement("UsersList", new XElement("SystemName", SystemInformation.ComputerName), new XElement("UserName", SystemInformation.ComputerName), new XElement("ImagePath", _filesPath + "\\insta.jpg"), new XElement("PhotoPath", _filesPath + "\\NoPhoto.png"), new XElement("UserStatus", "Available"), new XElement("CustomStatus", "Available"), new XElement("theme", "000000")));
xmlDoc.Save("C:\\config.xml");
于 2013-05-02T07:52:18.523 回答