本文整理匯總了C#中System.Xml.Linq.XElement.SetAttributeValue方法的典型用法代碼示例。如果您正苦於以下問題:C# XElement.SetAttributeValue方法的具體用法?C# XElement.SetAttributeValue怎麽用?C# XElement.SetAttributeValue使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Xml.Linq.XElement
的用法示例。
在下文中一共展示了XElement.SetAttributeValue方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: ExportGamesToXml
private static void ExportGamesToXml(IEnumerable<FinishedGame> games)
{
var doc = new XDocument();
var rootNode = new XElement("games");
doc.Add(rootNode);
foreach (var game in games)
{
var gameNode = new XElement("game");
gameNode.SetAttributeValue("name", game.Name);
if (game.Duration != null)
{
gameNode.SetAttributeValue("duration", game.Duration);
}
var usersNode = new XElement("users");
gameNode.Add(usersNode);
foreach (var user in game.Users)
{
var userNode = new XElement("user");
userNode.SetAttributeValue("username", user.Username);
userNode.SetAttributeValue("ip-address", user.IpAddress);
usersNode.Add(userNode);
}
rootNode.Add(gameNode);
}
doc.Save(ExportPath + Filename);
Console.WriteLine("File path: {0}", Path.GetFullPath(ExportPath + Filename));
}
示例2: Generate
public static void Generate()
{
using (var db = new SalesContext())
{
var sales = new XElement("sales");
foreach (var supermarket in db.Supermarkets)
{
var sale = new XElement("sale");
sale.SetAttributeValue("vendor", supermarket.Name);
var records = db.Records
.Where(x => x.Supermarket.Id == supermarket.Id)
.GroupBy(x => x.Date)
.OrderBy(x => x.Key)
.Select(x => new { Date = x.Key, Sum = x.Sum(y => y.Quantity * y.UnitPrice) });
foreach (var record in records)
{
var summary = new XElement("summary");
summary.SetAttributeValue("date", record.Date.ToShortDateString());
summary.SetAttributeValue("total-sum", record.Sum.ToString("00"));
sale.Add(summary);
}
sales.Add(sale);
}
sales.Save(FilePath);
//Console.WriteLine(File.ReadAllText(FilePath));
}
}
示例3: GetData
public XElement GetData()
{
XElement data = new XElement(XMLName);
data.SetAttributeValue("Name", Name);
data.SetAttributeValue("Type", Type);
return data;
}
示例4: HandleTarget
private void HandleTarget(BSharpBuilderWriteTarget target) {
foreach (var bsClass in target.Entity.Elements()) {
var bSharpClass = new XElement(BSharpBuilderDefaults.BSharpClassContainerName);
var bSharpIndexSet = new XElement(
BSharpBuilderDefaults.DefaultClassIndexContainerName,
bSharpClass
);
var writeTarget = new BSharpBuilderWriteTarget {
Directory = Project.GetOutputDirectory(),
Entity = bSharpIndexSet,
EntityContainerName = BSharpBuilderDefaults.DefaultClassIndexContainerName,
Extension = BSharpBuilderDefaults.IndexFileExtension,
Filename = BSharpBuilderDefaults.IndexFileName,
MergeIfExists = true
};
WriteIndexAttributeIfExists(bSharpClass, bsClass,BSharpSyntax.ClassNameAttribute);
WriteIndexAttributeIfExists(bSharpClass, bsClass, BSharpSyntax.ClassPrototypeAttribute);
WriteIndexAttributeIfExists(bSharpClass, bsClass, BSharpSyntax.ClassRuntimeAttribute);
bSharpClass.SetAttributeValue("file", target.Path.Remove(0, Project.GetOutputDirectory().Length).Replace("\\","/"));
if (bsClass.Attribute(BSharpSyntax.ClassFullNameAttribute) != null)
{
bSharpClass.SetAttributeValue(BSharpSyntax.Namespace, BSharpBuilderClassUtils.GetNamespace(bsClass.Attribute(BSharpSyntax.ClassFullNameAttribute).Value));
}
WriteManager.Add(writeTarget);
}
}
示例5: CreateXDT
private string CreateXDT(BuildConfig config)
{
XNamespace xdt = "http://schemas.microsoft.com/XML-Document-Transform";
var doc = XDocument.Parse("<?xml version=\"1.0\"?><configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\"></configuration>");
var connectionStrings = new XElement(XName.Get("connectionStrings"));
doc.Root.Add(connectionStrings);
foreach (var item in config.ConnectionStrings)
{
XElement cnstr = new XElement(XName.Get("add"));
connectionStrings.Add(cnstr);
cnstr.SetAttributeValue(XName.Get("name"), item.Name);
cnstr.SetAttributeValue(XName.Get("connectionString"), item.ConnectionString);
cnstr.SetAttributeValue(xdt + "Transform", "SetAttributes");
cnstr.SetAttributeValue(xdt + "Locator", "Match(name)");
if(item.ProviderName!=null){
cnstr.SetAttributeValue(XName.Get("providerName"), item.ProviderName);
}
}
var appSettings = new XElement(XName.Get("appSettings"));
doc.Root.Add(appSettings);
foreach (var item in config.AppSettings)
{
XElement cnstr = new XElement(XName.Get("add"));
appSettings.Add(cnstr);
cnstr.SetAttributeValue(XName.Get("key"), item.Key);
cnstr.SetAttributeValue(XName.Get("value"), item.Value);
cnstr.SetAttributeValue(xdt + "Transform", "SetAttributes");
cnstr.SetAttributeValue(xdt + "Locator", "Match(key)");
}
return doc.ToString(SaveOptions.OmitDuplicateNamespaces);
}
示例6: DumpAssembly
public static XElement DumpAssembly(string assemblyFile, bool includeParentMemebers=false)
{
AssemblyDefinition source = AssemblyDefinition.ReadAssembly(assemblyFile);
if (source == null)
{
return null;
}
List<TypeDefinition> sourceTypes;
try
{
sourceTypes = source.Modules.SelectMany(m => m.Types).Where(t => t.IsPublic).ToList();
(source.MainModule.AssemblyResolver as DefaultAssemblyResolver).AddSearchDirectory(Path.GetDirectoryName(assemblyFile));
sourceTypes.AddRange(source.Modules.SelectMany(m => m.ExportedTypes).Select(r => r.Resolve()).Where(t => t.IsPublic));
}
catch (Exception)
{
//we don't care about broken or empty files
return null;
}
XElement asmXml = new XElement("Assembly");
asmXml.SetAttributeValue("Name", source.Name.Name);
asmXml.SetAttributeValue("Info", source.FullName);
foreach (TypeDefinition typeDefinition in sourceTypes)
{
asmXml.Add(DumpType(typeDefinition, includeParentMemebers));
}
return asmXml;
}
示例7: FeatureActivated
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
// Add the Mobile Web Part Adapter to the compat.browser file
SPWebApplication webApp = null;
if (properties.Feature.Parent is SPSite)
{
SPSite spSite = properties.Feature.Parent as SPSite;
webApp = spSite.WebApplication;
}
else if (properties.Feature.Parent is SPWebApplication)
{
webApp = properties.Feature.Parent as SPWebApplication;
}
String pathToCompatBrowser = webApp.IisSettings[SPUrlZone.Default].Path + @"\App_Browsers\compat.browser";
XElement compatBrowser = XElement.Load(pathToCompatBrowser);
// Get the node for the default browser.
XElement controlAdapters = compatBrowser.XPathSelectElement("./browser[@refID = \"default\"]/controlAdapters");
// Create and add the markup.
XElement newAdapter = new XElement("adapter");
newAdapter.SetAttributeValue("controlType", controlType);
newAdapter.SetAttributeValue("adapterType", webPartFQN);
controlAdapters.Add(newAdapter);
compatBrowser.Save(pathToCompatBrowser);
}
catch { }
}
示例8: RemainingQuantities
/// <summary>
/// Exports to XML all remaining products and the shops they are located in
/// </summary>
/// <param name="db"></param>
public static void RemainingQuantities()
{
//create root element and database
var db = new SQLServerContextFactory().Create();
XElement root = new XElement("products");
//make a collection with all the data you want to export to XML. Use as many joins as needed
var products = db.Products.OrderBy(p => p.QuantityInStock);
//go through all items in the collection
foreach (var product in products)
{
//for every nested element you must create new instance of XElement
XElement currentProduct = new XElement("product"); //create tag
currentProduct.SetAttributeValue("name", product.Name); //set attribute
currentProduct.SetAttributeValue("description", product.Description); //set another attribute
XElement productInfo = new XElement("info"); //nest element after "Product"
productInfo.Add(new XElement("price", product.Price)); //add element inside "Info"
//you can create those as new XElement like the creation of "Info"
productInfo.Add(new XElement("quantity", product.QuantityInStock));
//add info to product
currentProduct.Add(productInfo);
//add current set of tags to root
root.Add(currentProduct);
}
string methodName = MethodBase.GetCurrentMethod().Name;
root.Save(Helpers.NamingFactory.BuildName(methodName, fileType));
}
示例9: Write
public void Write(Project project)
{
var file = Path.Combine(project.Directory, PackagesConfig);
XElement document;
if (_fileSystem.FileExists(file))
{
document = XElement.Load(file);
document.RemoveAll();
}
else
{
document = new XElement("packages");
}
project.Dependencies.Each(x =>
{
var package = new XElement("package");
package.SetAttributeValue("id", x.Name);
// TODO -- Make this easier to query
var solutionLevel = project.Solution.Dependencies.Find(x.Name);
package.SetAttributeValue("version", solutionLevel.Version.ToString());
// TODO -- Probably shouldn't hardcode this...
package.SetAttributeValue("targetFramework", "net40");
document.Add(package);
});
document.Save(file);
}
示例10: GetPlaceResultForMobile
public static ICollection<XElement> GetPlaceResultForMobile(Mobile.Server.Transaction transaction, Token token)
{
ICollection<XElement> elements = new List<XElement>();
if (token != null && token.AppType == AppType.Mobile)
{
Token placeToken = new Token(token.UserID, token.UserType, AppType.TradingConsole);
string tranCode;
TransactionError error = Application.Default.TradingConsoleServer.Place(placeToken, Application.Default.StateServer, transaction.ToXmlNode(), out tranCode);
if (error == TransactionError.Action_ShouldAutoFill)
{
error = TransactionError.OK;
}
foreach (Mobile.Server.Order order in transaction.Orders)
{
XElement orderErrorElement = new XElement("Order");
orderErrorElement.SetAttributeValue("Id", order.Id);
orderErrorElement.SetAttributeValue("ErrorCode", error.ToString());
elements.Add(orderErrorElement);
}
Mobile.Manager.UpdateWorkingOrder(token, transaction.Id, error);
return elements;
}
return null;
}
示例11: ProjectOpened
public static void ProjectOpened(Project project)
{
XDocument document;
if (!File.Exists(Path.Combine(MainWindow.UserPath, "Settings", "recent.xml")))
{
document = new XDocument();
document.Add(new XElement("projects"));
}
else
document = XDocument.Load(Path.Combine(MainWindow.UserPath, "Settings", "recent.xml"));
var newProject = new XElement("project");
newProject.SetAttributeValue("config", project.File);
newProject.SetAttributeValue("name", project.Name);
XElement toRemove = null;
foreach (var element in document.Root.Elements())
{
if (element.Attribute("config").Value == newProject.Attribute("config").Value)
{
toRemove = element;
break;
}
}
if (toRemove != null)
toRemove.Remove();
document.Root.AddFirst(newProject);
if (document.Root.Elements().Count() > 10)
{
var elements = document.Root.Elements().Take(10);
document.Root.RemoveAll();
document.Root.Add(elements);
}
document.Save(Path.Combine(MainWindow.UserPath, "Settings", "recent.xml"));
}
示例12: SaveBundleFromViewModel
public static void SaveBundleFromViewModel(BundleViewModel bundle, string bundleType)
{
var doc = XDocument.Load(HttpContext.Current.Server.MapPath(Config.BundlesConfigPath));
var bundleEl = new XElement(bundleType + "Bundle");
if (doc.Descendants(bundleType + "Bundle").Any(x => x.Attribute("virtualPath").Value == bundle.VirtualPath))
bundleEl =
doc.Descendants(bundleType + "Bundle")
.Single(x => x.Attribute("virtualPath").Value == bundle.VirtualPath);
else
{
bundleEl.SetAttributeValue("virtualPath", bundle.VirtualPath);
doc.Descendants("bundles").Single().Add(bundleEl);
}
bundleEl.SetAttributeValue("disableMinification", bundle.DisableMinification.ToString());
bundleEl.Elements().Remove();
if (bundle.Files != null)
{
foreach (var file in bundle.Files)
{
var includeEl = new XElement("include");
includeEl.SetAttributeValue("virtualPath", file);
bundleEl.Add(includeEl);
}
}
doc.Save(HttpContext.Current.Server.MapPath(Config.BundlesConfigPath));
HttpRuntime.UnloadAppDomain();
}
示例13: Generate
public XElement Generate(TestCase testCase)
{
XElement main = new XElement("div");
XElement tr = new XElement("tr");
XElement tdName = new XElement("td", testCase.Desription);
XElement tdStatus = new XElement("td", testCase.Result);
XElement tdTime = new XElement("td", testCase.Time);
XElement trMessage = new XElement("tr");
XElement tdMessage = new XElement("td");
if (testCase.Message != null || testCase.StackTrace != null)
{
XElement preMessage = new XElement("pre", testCase.Message);
XElement preStackTrace = new XElement("pre", testCase.StackTrace);
tdMessage.SetValue("MESSAGE:\n");
tdMessage.Add(preMessage);
tdMessage.Add(preStackTrace);
trMessage.Add(tdMessage);
}
else if (!string.IsNullOrEmpty(testCase.Reason))
{
XElement reasonMessage = new XElement("pre", testCase.Reason);
tdMessage.Add(reasonMessage);
trMessage.Add(tdMessage);
}
tr.Add(tdName);
tr.Add(tdStatus);
tr.Add(tdTime);
main.Add(tr);
main.Add(trMessage);
tdName.SetAttributeValue("style", "text-align:left;");
trMessage.SetAttributeValue("style", "font-size:11px; text-align:left;");
trMessage.SetAttributeValue("bgcolor", "lightgrey");
tdMessage.SetAttributeValue("colspan", "3");
switch (testCase.Result)
{
case "Success":
tdStatus.SetAttributeValue("bgcolor", "green");
break;
case "Ignored":
tdStatus.SetAttributeValue("bgcolor", "yellow");
break;
case "Failure":
tdStatus.SetAttributeValue("bgcolor", "red");
break;
default:
break;
}
return main;
}
示例14: CreateXml
public static void CreateXml(string filePath)
{
using (SupermarketDBContext sqldb = new SupermarketDBContext())
{
string format = "dd-MMM-yyyy";
XElement sales = new XElement("sales");
foreach (var vendor in sqldb.Vendors.ToList().Where(
x=> x.Products.Any(y => y.SalesReports.Count > 0)))
{
XElement elSale = new XElement("sale");
elSale.SetAttributeValue("vendor", vendor.VendorName.ToString());
foreach (var product in vendor.Products.ToList())
{
foreach (var report in product.SalesReports.ToList())
{
XElement summary = new XElement("summary");
summary.SetAttributeValue("date", report.ReportDate.ToString(format));
summary.SetAttributeValue("total-sum", report.Sum.ToString());
elSale.Add(summary);
}
}
sales.Add(elSale);
}
sales.Save(filePath);
}
}
示例15: UpdateVs2010Compatibility
void UpdateVs2010Compatibility(XDocument document, string file) {
var elements = document.Descendants().Where(element
=> element.Name.LocalName == "VSToolsPath" || element.Name.LocalName == "VisualStudioVersion" );
var xElements = elements as XElement[] ?? elements.ToArray();
bool save=xElements.Any();
xElements.Remove();
elements=document.Descendants().Where(element
=> element.Name.LocalName == "Import" &&
(element.Attribute("Project").Value.StartsWith("$(MSBuildExtensionsPath)")||
element.Attribute("Project").Value.StartsWith("$(MSBuildExtensionsPath32)")));
var enumerable = elements as XElement[] ?? elements.ToArray();
if (!save)
save = enumerable.Any();
if (IsWeb(document, GetOutputType(document))&& !document.Descendants().Any(element =>
element.Name.LocalName == "Import" && element.Attribute("Project").Value.StartsWith("$(VSToolsPath)")&&
element.Attribute("Condition").Value.StartsWith("'$(VSToolsPath)' != ''"))) {
var element = new XElement(_xNamespace+"Import");
element.SetAttributeValue("Project",@"$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets");
element.SetAttributeValue("Condition", @"'$(VSToolsPath)' != ''");
Debug.Assert(document.Root != null, "document.Root != null");
document.Root.Add(element);
save = true;
}
enumerable.Remove();
if (save)
DocumentHelper.Save(document, file);
}