如何检查字符串是否存在于xml节点的值asp.net中

时间:2012-10-31 10:30:17

标签: c# asp.net .net-3.5

我的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>

我想获得“link”中包含字符串“manager”的员工的“id”

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

使用linq to 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);

答案 2 :(得分: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");