I've got a XML file that contains this data:
<?xml version="1.0" encoding="iso-8859-1" ?>
<university>
<lecture>
<class>English</class>
<hours>3</hours>
<pupils>30</pupils>
</lecture>
<lecture>
<class>Math</class>
<hours>4</hours>
<pupils>27</pupils
</lecture>
<lecture>
<class>Science</class>
<hours>2</hours>
<pupils>25</pupils>
</lecture>
</university>
Is it possible if I can get an XQuery code that produces this output (below) for me?
<table>
<tr>
<td>English class runs for 3 with 30 pupils</td>
<td>Math class runs for 4 with 26 pupils</td>
<td>Science class runs for 2 with 25 pupils</td>
</tr>
</table>
EDIT: Below is my attempt:
let $classroom := doc("uni.xml")/university/lecture/class
let $hr := doc("uni.xml")/university/lecture/hours
let $pupl := doc("uni.xml")/university/lecture/pupils
<tr>
<table>
for $a in $classroom,
$b in $hr,
$c in $pupl
return <td>{$a} class runs for {$b} with {$c} pupils</td>
</tr>
</table>
I get an error saying I need to return a value, which I already did. If I take out the tr and table tags, it works, but gives me an endless loop result.
Responding to the updated XML, and a bit of your attempted XQuery style which using variables, I'd suggest something like this :
<table>
<tr>
{
for $lecture in doc("uni.xml")/university/lecture
let $class := $lecture/class/string()
let $hours := $lecture/hours/string()
let $pupils := $lecture/pupils/string()
return
<td>{$class} class runs for {$hours} with {$pupils} pupils</td>
}
</tr>
</table>
Demo : http://www.xpathtester.com/xquery/33e31b342098712e331285bda3010e0c
Basically, the query loop through common parent elements that contains all the needed information; the lecture elements. Then use simple relative XPath/XQuery to extract data from each lecture to produce the required output.
Related
I am currently working on a way to get a distribution list for all users registered to our application. We are using a SQL server to store information, however, due to a move to a non-relational DB schema in the near future, most of our data is stored in one field as a JSON string (It's a VARCHAR(max) field that looks like JSON). When we serve this data back to our Java controllers, we convert the String into a JSON Object. As my question would most likely indicate, the list of users is located in this JSON string. While I know I can just do SELECT JSON_DATA FROM MYTABLE to get all entries of this field, convert it in Java, and get the users field that way, I would be essentially returning a TON of data and throwing away 95% of it.
I was wondering if there is a way in SQL Server to parse a JSON string? Essentially what I want to do is with the following table:
<table style="width:100%" border="1">
<tr>
<th>ID</th>
<th>JSON_DATA</th>
</tr>
<tr>
<td>1</td>
<td>{"data":data,"users":["User1", "User2"]}</td>
</tr>
<tr>
<td>2</td>
<td>{"data":data2,"users":["User2", "User3"]}</td>
</tr>
</table>
I want to return from my SQL routine a list of all unique users.
I think this might give you what you need:
Select JSON_QUERY([fieldName], $.users)
Here's a link to check out too: https://learn.microsoft.com/en-us/sql/t-sql/functions/json-query-transact-sql?view=sql-server-2017
Without native JSON support, I'm afraid you're looking a good ol' string parsing. This should get you part of the way: it returns a single string with
"User1", "User2", "User2", "User3"
DECLARE #ThisUserString VARCHAR(255)
, #FullUserString VARCHAR(255) = ''
DECLARE #xmlSTring VARCHAR(MAX) =
'<table style="width:100%" border="1">
<tr>
<th>ID</th>
<th>JSON_DATA</th>
</tr>
<tr>
<td>1</td>
<td>{"data":data,"users":["User1", "User2"]}</td>
</tr>
<tr>
<td>2</td>
<td>{"data":data2,"users":["User2", "User3"]}</td>
</tr>
</table>'
WHILE CHARINDEX('[', #xmlSTring) > 0
BEGIN
-- Find the next set of users, like ["User1", "User2"]
SELECT #ThisUserString =
SUBSTRING(
#xmlSTring
, /*start*/ CHARINDEX('[', #xmlSTring)
, /*length*/ CHARINDEX(']', #xmlSTring) - CHARINDEX('[', #xmlSTring) + 1
)
-- Add them to the list of all users, like "User1", "User2"
SELECT #FullUserString += ', ' +
SUBSTRING(
#xmlSTring
, /*start*/ CHARINDEX('[', #xmlSTring) + 1
, /*length*/ CHARINDEX(']', #xmlSTring) - CHARINDEX('[', #xmlSTring) - 1
)
-- And remove this set from the string so our WHILE loop will end sometime:
SET #xmlSTring = REPLACE(#xmlSTring, #ThisUserString, '')
END
SET #FullUserString = RIGHT(#FullUserString, LEN(#FullUserString) - 2) -- remove the initial comma
SELECT #FullUserString
Im just asking how to implement Substring code in Razor Html DisplayFor
Actually It was working before then I added the Substring to get the first 5 number in the table then I encountered an error
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Here are my set of Codes:
<tbody>
#for (var i = 0; i < Model.Cards.Count; ++i)
{
var counter = i + 1;
<tr>
<td valign="middle">
<p class="small">#counter</p>
</td>
<td valign="middle">
<p class="small">#Html.DisplayFor(x => x.Cards[i].Number.Substring(0,5))</p>
</td>
</tr>
}
</tbody>
Thanks in Advance !
As Stephen said in comments, using .Substring in the middle of your view doesn't really make sens.
Instead, in your ViewModel (the one which defines your Number property), add the following property :
public string DisplayableNumber => Number.Length > 5 ? Number.ToString().Substring(0, 5) : "WhatYouWantHere";
This will work for C# 5+, else you can use the old way and initialize it in the default constructor.
Then, use it in your view :
#Html.DisplayFor(x => x.Cards[i].DisplayableNumber)
Plus, this is good practice to use this type of property in ViewModel, as Views should't handle any logic.
I have a bunch of pandas dataframes in a list that I need to convert to html tables. The html code for each individual dataframe looks good, however when I append the html to a list I end up with a bunch of \n characters showing on my webpage. Can anyone tell me how to get rid of them?
python code:
dataframe_html = []
table_dic = {}
for df in dataframes:
frame = df.to_html(classes="table table-hover")
dataframe_html.append(frame) #this is the line where all the \n get added
table_dic.update({'dataframe_html':dataframe_html})
return render(request,'InterfaceApp/FileProcessor_results.html',table_dic)
html code:
<div class="table-responsive">
{{ dataframe_html | safe }}
</div>
Shows up like this:
'
Can anyone help me out with this??
To display 3 separate tables, join the list of HTML strings into a single string:
dataframe_html = u''.join(dataframe_html)
for df in dataframes:
frame = df.to_html(classes="table table-hover")
dataframe_html.append(frame)
dataframe_html = u''.join(dataframe_html)
table_dic = {'dataframe_html':dataframe_html}
return render(request,'InterfaceApp/FileProcessor_results.html',table_dic)
FWIW this late in the game:
I had originally had:
response = render_template('table_display.html', query_results=[df_html], query_name='Quality Item Query')
and was getting an entire row of \n characters. Changed to below and the newlines disappeared.
response = render_template('table_display.html', query_results=df_html, query_name='Quality Item Query')
Even later in the game...
I stumbled upon this thread when having the same problem. Hopefully, the below helps someone.
I assigned the results of df.to_html() to a (nested) list and got the new lines when rendering in my Jinja template. The solution inspired by #AlliDeacon was to index the result again when rendering
Python code:
result[0][0] = df.to_html()
Jinja template:
<div>Table: {{ result[0][0][0] }}</div>
Refer output of the following code for illustration of the difference between a (sub-)list and a list element:
df = pd.DataFrame([['a','b']],
columns=['col_A', 'col_B'])
tmp = []
tmp.append(df.to_html(index=False))
print(tmp)
print(tmp[0])
Result:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>col_A</th>
<th>col_B</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>b</td>
</tr>
</tbody>
</table>
Even more than late than late to the game. The issue with the newline characters is that the frame is by default in JSON when passed from your app to Jinja. The \n's are being read literally, but the table gets constructed from what follows inside the JSON string. There are two cases to deal with this, depending on the method of passing your dataframe:
Case 1: Passing a dataframe with render_template:
Pass the frame in your app without the "df.to_html". Within your html use the Jinja2 syntax to obtain a clean frame without any newline characters:
{{ df_html.to_html(classes="your-fancy-table-class") | safe }}
Case 2: Passing with json.dumps to be retrieved in JS
In case you send your frame via a response, e.g. post Ajax request, pass the frame with df.to_html() as you did:
#app.route('/foo', methods=['POST']) #load and return the frame route
def foo():
# df = pd.DataFrame...
return json.dumps({"response": df.to_html}
Then in your JS, load the clean frame without the newline characters in HTML from your response with:
JSON.parse(data).response;
$("#your-table-wrapper").html(response);
Say I have a nested object literal, and I want to display its contents in a table.
If the object is 2 levels deep, I can use:
<table>
<thead>
<tr>
<td>key</td>
<td>value</td>
</tr>
</thead>
<tbody ng-repeat="(key01, value01) in data">
<tr ng-repeat="(key02, value02) in value01">
<td>{{key02}}</td>
<td>{{value02}}</td>
</tr>
</tbody>
</table>
If I have a nested object that is 3 or 4 levels deep, using a similar method how would I display the data in a table? The best I have is from this previously answered question, however I do not want conduct this logic in a controller, as suggested here.
I need a way to nest more than 2 ng-Repeats as seen above since in my application, the key names are variable at data generation.
An example of a 3 level deep nest object:
$scope.someVar = { 'data': {
'A': {
'x':'someValue'
},
'B': {
'y':'anotherValue'
}
}
}
Unfortunately for your stated requirements it's not possible. The table element structure just doesn't have the kind of nesting you want. I know you said you don't want to do this in a controller but that's probably the best way of doing this as a table is a way of representing 2D information, not more.
Also it should be said that if you're putting a lot of data in these nested ngRepeats you're very likely to slow the browser down to an unusable state.
If you really can't do some kind of transformation in the controller (which is easier on the browser as it's done once, instead of every time something changes...) you would have to use div's with table like styling. Try here (link)
u should be doing something like this
$scope.someVar = { 'data': {
'A': {
'x':'someValue'
},
'B': {
'y':'anotherValue'
}
}
then you have to use ng-repeat like this,
<tbody ng-repeat="(key01, value01) in someVar.data">
<tr ng-repeat="(key02, value02) in value01">
I am trying to get an HTML page like: http://jsbin.com/awoco.
This is a JSP page so it will include scriptlets. Final HTML output will be kind of like this (tags unclosed to save space):
<%
Iterator it = MyList.iterator()
While (it.hasNext())
SomeClass all = it.next();
SomeClass a = it.next();
SomeClass b = it.next();
%>
<tr>
<td rowspan=3 valign=top>Red<td><%=all.Name()%><td><%=all.price()%><td><%=all.originalPrice()%>
</tr>
<tr>
<td><%=a.Name()%><td><%=a.price()%><td><%=a.originalPrice()%>
</tr>
<tr >
<td><%=b.Name()%><td><%=b.price()%><td><%=b.originalPrice()%>
</tr>
As you can see, I have to call next() 3 times inside the while loop. This is because the source of the data is a List populated that way, and I have to show the data in the exact same manner as in the link provided above.
Is there a way to change the HTML output somehow so that I don't have to call next() more than once, but still get the same table structure?
Change your data structures. MyList should be list of (something like) AgregateClass which will contain 3 members of type SomeClass (all,a,b) and then simply iterate through MyList.
Just few tips:
If you are using Struts2 you can use <s:iterator> tag to iterate through collections. documentation
Since JSP 2.0 or so you can write ${b.price} instead of <%=b.price()%>
You should change tags you added to your question as it has nothing to do with html or css.